diff --git a/build.js b/build.js index b348d9a04..a4478923b 100755 --- a/build.js +++ b/build.js @@ -99,7 +99,7 @@ 'filter': ['createCallback', 'isArray'], 'find': ['createCallback', 'forEach'], 'first': [], - 'flatten': ['isArray'], + 'flatten': ['createCallback', 'isArray'], 'forEach': ['createCallback', 'isArguments', 'isArray', 'isString'], 'forIn': ['createCallback', 'isArguments'], 'forOwn': ['createCallback', 'isArguments'], @@ -1667,6 +1667,7 @@ } if (isUnderscore) { dependencyMap.contains = _.without(dependencyMap.contains, 'isString'); + dependencyMap.flatten = _.without(dependencyMap.flatten, 'createCallback'); dependencyMap.isEmpty = ['isArray', 'isString']; dependencyMap.isEqual = _.without(dependencyMap.isEqual, 'forIn', 'isArguments'); dependencyMap.max = _.without(dependencyMap.max, 'isString'); @@ -1843,7 +1844,26 @@ ' result.push(value);', ' }', ' }', - ' return result', + ' return result;', + '}' + ].join('\n')); + + // replace `_.flatten` + source = replaceFunction(source, 'flatten', [ + 'function flatten(array, isShallow) {', + ' var index = -1,', + ' length = array ? array.length : 0,', + ' result = [];', + '' , + ' while (++index < length) {', + ' var value = array[index];', + ' if (isArray(value)) {', + ' push.apply(result, isShallow ? value : flatten(value));', + ' } else {', + ' result.push(value);', + ' }', + ' }', + ' return result;', '}' ].join('\n')); diff --git a/dist/lodash.compat.js b/dist/lodash.compat.js index 43d94941b..4f4f6a8d1 100644 --- a/dist/lodash.compat.js +++ b/dist/lodash.compat.js @@ -3320,14 +3320,28 @@ } /** - * Flattens a nested array (the nesting can be to any depth). If `shallow` is - * truthy, `array` will only be flattened a single level. + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truthy, `array` will only be flattened a single level. If `callback` + * is passed, each element of `array` is passed through a callback` before + * flattening. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. - * @param {Boolean} shallow A flag to indicate only flattening a single level. + * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * @@ -3336,18 +3350,38 @@ * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; + * + * var stooges = [ + * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(stooges, 'quotes'); + * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ - function flatten(array, shallow) { + function flatten(array, isShallow, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = isShallow; + isShallow = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg); + } while (++index < length) { var value = array[index]; - + if (callback) { + value = callback(value, index, array); + } // recursively flatten arrays (susceptible to call stack limits) if (isArray(value)) { - push.apply(result, shallow ? value : flatten(value)); + push.apply(result, isShallow ? value : flatten(value)); } else { result.push(value); } diff --git a/dist/lodash.compat.min.js b/dist/lodash.compat.min.js index 68bb5b171..e6c25da21 100644 --- a/dist/lodash.compat.min.js +++ b/dist/lodash.compat.min.js @@ -17,9 +17,10 @@ n[e]=o});return n}function ut(n){for(var t=-1,e=Ne(n),r=e.length,u=Nt(r);++tu&&(u=i)}}else t=!t&&et(n)?B:a.createCallback(t,e),Oe(n,function(n,e,a){e=t(n,e,a),e>r&&(r=e,u=n)});return u}function st(n,t,e,r){var u=3>arguments.length;if(t=a.createCallback(t,r,4),Ie(n)){var o=-1,i=n.length;for(u&&(e=n[++o]);++oarguments.length;if(typeof o!="number")var f=Ne(n),o=f.length; else de&&et(n)&&(u=n.split(""));return t=a.createCallback(t,r,4),ct(n,function(n,r,a){r=f?f[--o]:--o,e=i?(i=!1,u[r]):t(e,u[r],r,a)}),e}function gt(n,t,e){var r;if(t=a.createCallback(t,e),Ie(n)){e=-1;for(var u=n.length;++ee?ae(0,u+e):e||0)-1;else if(e)return r=bt(n,t),n[r]===t?r:-1;for(;++r>>1,e(n[r])mt(f,p))&&((e||c)&&f.push(p),i.push(r))}return i}function kt(n,t){for(var e=-1,r=n?n.length:0,u={};++ee?ae(0,u+e):e||0)-1;else if(e)return r=bt(n,t),n[r]===t?r:-1;for(;++r>>1,e(n[r])mt(f,p))&&((e||c)&&f.push(p),i.push(r))}return i +}function kt(n,t){for(var e=-1,r=n?n.length:0,u={};++e/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:h,variable:"",imports:{_:a}}; var je={a:"q,w,g",l:"var a=arguments,b=0,c=typeof g=='number'?2:a.length;while(++b":">",'"':""","'":"'"},$e=X(Ae),Fe=D(je,{l:je.l.replace(";",";if(c>3&&typeof a[c-2]=='function'){var d=o.createCallback(a[--c-1],a[c--],2);}else if(c>2&&typeof a[c-1]=='function'){d=a[--c];}"),h:"u[i]=d?d(u[i],m[i]):m[i]"}),qe=D(je);Z(/x/)&&(Z=function(n){return n instanceof Ft||Yt.call(n)==C});var Be=Ht?function(n){if(!n||typeof n!="object")return!1;var t=n.valueOf,e=typeof t=="function"&&(e=Ht(t))&&Ht(e); diff --git a/dist/lodash.js b/dist/lodash.js index 13b46afe2..db7cb45fa 100644 --- a/dist/lodash.js +++ b/dist/lodash.js @@ -3164,14 +3164,28 @@ } /** - * Flattens a nested array (the nesting can be to any depth). If `shallow` is - * truthy, `array` will only be flattened a single level. + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truthy, `array` will only be flattened a single level. If `callback` + * is passed, each element of `array` is passed through a callback` before + * flattening. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. - * @param {Boolean} shallow A flag to indicate only flattening a single level. + * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * @@ -3180,18 +3194,38 @@ * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; + * + * var stooges = [ + * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(stooges, 'quotes'); + * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ - function flatten(array, shallow) { + function flatten(array, isShallow, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = isShallow; + isShallow = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg); + } while (++index < length) { var value = array[index]; - + if (callback) { + value = callback(value, index, array); + } // recursively flatten arrays (susceptible to call stack limits) if (isArray(value)) { - push.apply(result, shallow ? value : flatten(value)); + push.apply(result, isShallow ? value : flatten(value)); } else { result.push(value); } diff --git a/dist/lodash.min.js b/dist/lodash.min.js index a72bafe01..23d0bbc40 100644 --- a/dist/lodash.min.js +++ b/dist/lodash.min.js @@ -6,8 +6,8 @@ */ ;(function(n){function t(r){function a(n){return n&&typeof n=="object"&&Mt.call(n,"__wrapped__")?n:this instanceof a?(this.__wrapped__=n,void 0):new a(n)}function $(n,t,e){t||(t=0);var r=n.length,u=r-t>=(e||f);if(u){var a={};for(e=t-1;++et||typeof n=="undefined")return 1; if(ne?0:e);++re?0:e);++ru&&(u=i)}}else t=!t&&Y(n)?F:a.createCallback(t,e),se(n,function(n,e,a){e=t(n,e,a),e>r&&(r=e,u=n)});return u}function ft(n,t,e,r){var u=3>arguments.length; if(t=a.createCallback(t,r,4),he(n)){var o=-1,i=n.length;for(u&&(e=n[++o]);++oarguments.length;if(typeof u!="number")var i=ye(n),u=i.length;return t=a.createCallback(t,r,4),at(n,function(r,a,f){a=i?i[--u]:--u,e=o?(o=!1,n[a]):t(e,n[a],a,f)}),e}function lt(n,t,e){var r;if(t=a.createCallback(t,e),he(n)){e=-1;for(var u=n.length;++ee?Yt(0,u+e):e||0)-1;else if(e)return r=ht(n,t),n[r]===t?r:-1;for(;++r>>1,e(n[r])vt(f,p))&&((e||c)&&f.push(p),i.push(r))}return i}function mt(n,t){for(var e=-1,r=n?n.length:0,u={};++ee?Yt(0,u+e):e||0)-1; +else if(e)return r=ht(n,t),n[r]===t?r:-1;for(;++r>>1,e(n[r])vt(f,p))&&((e||c)&&f.push(p),i.push(r))}return i}function mt(n,t){for(var e=-1,r=n?n.length:0,u={};++e/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:h,variable:"",imports:{_:a}};var fe={a:"q,w,g",l:"var a=arguments,b=0,c=typeof g=='number'?2:a.length;while(++b":">",'"':""","'":"'"},de=J(me),be=R(fe,{l:fe.l.replace(";",";if(c>3&&typeof a[c-2]=='function'){var d=o.createCallback(a[--c-1],a[c--],2);}else if(c>2&&typeof a[c-1]=='function'){d=a[--c];}"),h:"u[i]=d?d(u[i],m[i]):m[i]"}),_e=R(fe),ke=function(n){if(!n||typeof n!="object")return!1;var t=n.valueOf,e=typeof t=="function"&&(e=Pt(t))&&Pt(e); -if(e)n=n==e||Pt(n)==e&&!U(n);else{var r=!1;!n||typeof n!="object"||U(n)?n=r:(t=n.constructor,!Q(t)||t instanceof t?(ve(n,function(n,t){r=t}),n=!1===r||Mt.call(n,r)):n=r)}return n},je=8==ne("08")?ne:function(n,t){return ne(Y(n)?n.replace(/^0+(?=.$)/,""):n,t||0)};return ue&&u&&typeof Ut=="function"&&(bt=dt(Ut,r)),a.after=function(n,t){return 1>n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},a.assign=be,a.at=function(n){for(var t=-1,e=Dt.apply($t,M(arguments,1)),r=e.length,u=wt(r);++t":">",'"':""","'":"'"},be=J(me),de=R(fe,{l:fe.l.replace(";",";if(c>3&&typeof a[c-2]=='function'){var d=o.createCallback(a[--c-1],a[c--],2);}else if(c>2&&typeof a[c-1]=='function'){d=a[--c];}"),h:"u[i]=d?d(u[i],m[i]):m[i]"}),_e=R(fe),ke=function(n){if(!n||typeof n!="object")return!1;var t=n.valueOf,e=typeof t=="function"&&(e=Pt(t))&&Pt(e); +if(e)n=n==e||Pt(n)==e&&!U(n);else{var r=!1;!n||typeof n!="object"||U(n)?n=r:(t=n.constructor,!Q(t)||t instanceof t?(ve(n,function(n,t){r=t}),n=!1===r||Mt.call(n,r)):n=r)}return n},je=8==ne("08")?ne:function(n,t){return ne(Y(n)?n.replace(/^0+(?=.$)/,""):n,t||0)};return ue&&u&&typeof Ut=="function"&&(dt=bt(Ut,r)),a.after=function(n,t){return 1>n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},a.assign=de,a.at=function(n){for(var t=-1,e=Dt.apply($t,M(arguments,1)),r=e.length,u=wt(r);++tvt(f,c)){o&&f.push(c);for(var p=e;--p;)if(!(r[p]||(r[p]=$(t[p],0,100)))(c))continue n;i.push(c) }}return i},a.invert=J,a.invoke=function(n,t){var e=M(arguments,2),r=-1,u=typeof t=="function",a=n?n.length:0,o=wt(typeof a=="number"?a:0);return at(n,function(n){o[++r]=(u?t:n[t]).apply(n,e)}),o},a.keys=ye,a.map=ot,a.max=it,a.memoize=function(n,t){var e={};return function(){var r=(t?t.apply(this,arguments):arguments[0])+"";return Mt.call(e,r)?e[r]:e[r]=n.apply(this,arguments)}},a.merge=Z,a.min=function(n,t,e){var r=1/0,u=r;if(!t&&he(n)){e=-1;for(var o=n.length;++evt(o,e,1))&&(u[e]=n)}),u},a.once=function(n){var t,e;return function(){return t?e:(t=!0,e=n.apply(this,arguments),n=null,e)}},a.pairs=function(n){for(var t=-1,e=ye(n),r=e.length,u=wt(r);++te?Yt(0,r+e):Zt(e,r-1))+1);r--;)if(n[r]===t)return r;return-1},a.mixin=kt,a.noConflict=function(){return r._=qt,this},a.parseInt=je,a.random=function(n,t){return null==n&&null==t&&(t=1),n=+n||0,null==t&&(t=n,n=0),n+zt(te()*((+t||0)-n+1))},a.reduce=ft,a.reduceRight=ct,a.result=function(n,t){var r=n?n[t]:e;return Q(r)?n[t]():r},a.runInContext=t,a.size=function(n){var t=n?n.length:0;return typeof t=="number"?t:ye(n).length -},a.some=lt,a.sortedIndex=ht,a.template=function(n,t,r){var u=a.templateSettings;n||(n=""),r=_e({},r,u);var o,i=_e({},r.imports,u.imports),u=ye(i),i=nt(i),f=0,c=r.interpolate||y,v="__p+='",c=Et((r.escape||y).source+"|"+c.source+"|"+(c===h?g:y).source+"|"+(r.evaluate||y).source+"|$","g");n.replace(c,function(t,e,r,u,a,i){return r||(r=u),v+=n.slice(f,i).replace(d,D),e&&(v+="'+__e("+e+")+'"),a&&(o=!0,v+="';"+a+";__p+='"),r&&(v+="'+((__t=("+r+"))==null?'':__t)+'"),f=i+t.length,t}),v+="';\n",c=r=r.variable,c||(r="obj",v="with("+r+"){"+v+"}"),v=(o?v.replace(l,""):v).replace(p,"$1").replace(s,"$1;"),v="function("+r+"){"+(c?"":r+"||("+r+"={});")+"var __t,__p='',__e=_.escape"+(o?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+v+"return __p}"; -try{var m=Ot(u,"return "+v).apply(e,i)}catch(b){throw b.source=v,b}return t?m(t):(m.source=v,m)},a.unescape=function(n){return null==n?"":(n+"").replace(c,K)},a.uniqueId=function(n){var t=++o;return(null==n?"":n+"")+t},a.all=et,a.any=lt,a.detect=ut,a.foldl=ft,a.foldr=ct,a.include=tt,a.inject=ft,ge(a,function(n,t){a.prototype[t]||(a.prototype[t]=function(){var t=[this.__wrapped__];return Kt.apply(t,arguments),n.apply(a,t)})}),a.first=pt,a.last=function(n,t,e){if(n){var r=0,u=n.length;if(typeof t!="number"&&null!=t){var o=u; +},a.some=lt,a.sortedIndex=ht,a.template=function(n,t,r){var u=a.templateSettings;n||(n=""),r=_e({},r,u);var o,i=_e({},r.imports,u.imports),u=ye(i),i=nt(i),f=0,c=r.interpolate||y,v="__p+='",c=Et((r.escape||y).source+"|"+c.source+"|"+(c===h?g:y).source+"|"+(r.evaluate||y).source+"|$","g");n.replace(c,function(t,e,r,u,a,i){return r||(r=u),v+=n.slice(f,i).replace(b,D),e&&(v+="'+__e("+e+")+'"),a&&(o=!0,v+="';"+a+";__p+='"),r&&(v+="'+((__t=("+r+"))==null?'':__t)+'"),f=i+t.length,t}),v+="';\n",c=r=r.variable,c||(r="obj",v="with("+r+"){"+v+"}"),v=(o?v.replace(l,""):v).replace(p,"$1").replace(s,"$1;"),v="function("+r+"){"+(c?"":r+"||("+r+"={});")+"var __t,__p='',__e=_.escape"+(o?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+v+"return __p}"; +try{var m=Ot(u,"return "+v).apply(e,i)}catch(d){throw d.source=v,d}return t?m(t):(m.source=v,m)},a.unescape=function(n){return null==n?"":(n+"").replace(c,K)},a.uniqueId=function(n){var t=++o;return(null==n?"":n+"")+t},a.all=et,a.any=lt,a.detect=ut,a.foldl=ft,a.foldr=ct,a.include=tt,a.inject=ft,ge(a,function(n,t){a.prototype[t]||(a.prototype[t]=function(){var t=[this.__wrapped__];return Kt.apply(t,arguments),n.apply(a,t)})}),a.first=pt,a.last=function(n,t,e){if(n){var r=0,u=n.length;if(typeof t!="number"&&null!=t){var o=u; for(t=a.createCallback(t,e);o--&&t(n[o],o,n);)r++}else if(r=t,null==r||e)return n[u-1];return M(n,Yt(0,u-r))}},a.take=pt,a.head=pt,ge(a,function(n,t){a.prototype[t]||(a.prototype[t]=function(t,e){var r=n(this.__wrapped__,t,e);return null==t||e&&typeof t!="function"?r:T(r)})}),a.VERSION="1.0.1",a.prototype.toString=function(){return this.__wrapped__+""},a.prototype.value=jt,a.prototype.valueOf=jt,se(["join","pop","shift"],function(n){var t=$t[n];a.prototype[n]=function(){return t.apply(this.__wrapped__,arguments) -}}),se(["push","reverse","sort","unshift"],function(n){var t=$t[n];a.prototype[n]=function(){return t.apply(this.__wrapped__,arguments),this}}),se(["concat","slice","splice"],function(n){var t=$t[n];a.prototype[n]=function(){return T(t.apply(this.__wrapped__,arguments))}}),a}var e,r=typeof exports=="object"&&exports,u=typeof module=="object"&&module&&module.exports==r&&module,a=typeof global=="object"&&global;a.global===a&&(n=a);var o=0,i={},f=30,c=/&(?:amp|lt|gt|quot|#39);/g,l=/\b__p\+='';/g,p=/\b(__p\+=)''\+/g,s=/(__e\(.*?\)|\b__t\))\+'';/g,v=/\w*$/,g=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,h=/<%=([\s\S]+?)%>/g,y=/($^)/,m=/[&<>"']/g,d=/['\n\r\t\u2028\u2029\\]/g,b="Array Boolean Date Function Math Number Object RegExp String _ attachEvent clearTimeout isFinite isNaN parseInt setImmediate setTimeout".split(" "),_="[object Arguments]",k="[object Array]",j="[object Boolean]",w="[object Date]",C="[object Number]",x="[object Object]",O="[object RegExp]",N="[object String]",S={"[object Function]":!1}; +}}),se(["push","reverse","sort","unshift"],function(n){var t=$t[n];a.prototype[n]=function(){return t.apply(this.__wrapped__,arguments),this}}),se(["concat","slice","splice"],function(n){var t=$t[n];a.prototype[n]=function(){return T(t.apply(this.__wrapped__,arguments))}}),a}var e,r=typeof exports=="object"&&exports,u=typeof module=="object"&&module&&module.exports==r&&module,a=typeof global=="object"&&global;a.global===a&&(n=a);var o=0,i={},f=30,c=/&(?:amp|lt|gt|quot|#39);/g,l=/\b__p\+='';/g,p=/\b(__p\+=)''\+/g,s=/(__e\(.*?\)|\b__t\))\+'';/g,v=/\w*$/,g=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,h=/<%=([\s\S]+?)%>/g,y=/($^)/,m=/[&<>"']/g,b=/['\n\r\t\u2028\u2029\\]/g,d="Array Boolean Date Function Math Number Object RegExp String _ attachEvent clearTimeout isFinite isNaN parseInt setImmediate setTimeout".split(" "),_="[object Arguments]",k="[object Array]",j="[object Boolean]",w="[object Date]",C="[object Number]",x="[object Object]",O="[object RegExp]",N="[object String]",S={"[object Function]":!1}; S[_]=S[k]=S[j]=S[w]=S[C]=S[x]=S[O]=S[N]=!0;var A={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},E={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},I=t();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(n._=I,define(function(){return I})):r&&!r.nodeType?u?(u.exports=I)._=I:r._=I:n._=I})(this); \ No newline at end of file diff --git a/dist/lodash.underscore.js b/dist/lodash.underscore.js index 4c719a05e..73a675797 100644 --- a/dist/lodash.underscore.js +++ b/dist/lodash.underscore.js @@ -2478,7 +2478,7 @@ result.push(value); } } - return result + return result; } /** @@ -2560,14 +2560,28 @@ } /** - * Flattens a nested array (the nesting can be to any depth). If `shallow` is - * truthy, `array` will only be flattened a single level. + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truthy, `array` will only be flattened a single level. If `callback` + * is passed, each element of `array` is passed through a callback` before + * flattening. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. - * @param {Boolean} shallow A flag to indicate only flattening a single level. + * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * @@ -2576,18 +2590,25 @@ * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; + * + * var stooges = [ + * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(stooges, 'quotes'); + * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ - function flatten(array, shallow) { + function flatten(array, isShallow) { var index = -1, length = array ? array.length : 0, result = []; - + while (++index < length) { var value = array[index]; - - // recursively flatten arrays (susceptible to call stack limits) if (isArray(value)) { - push.apply(result, shallow ? value : flatten(value)); + push.apply(result, isShallow ? value : flatten(value)); } else { result.push(value); } diff --git a/doc/README.md b/doc/README.md index e7b456147..2920bdee7 100644 --- a/doc/README.md +++ b/doc/README.md @@ -10,7 +10,7 @@ * [`_.difference`](#_differencearray--array1-array2-) * [`_.drop`](#_restarray--callbackn1-thisarg) * [`_.first`](#_firstarray--callbackn-thisarg) -* [`_.flatten`](#_flattenarray-shallow) +* [`_.flatten`](#_flattenarray--isshallowfalse-callbackidentity-thisarg) * [`_.head`](#_firstarray--callbackn-thisarg) * [`_.indexOf`](#_indexofarray-value--fromindex0) * [`_.initial`](#_initialarray--callbackn1-thisarg) @@ -309,14 +309,20 @@ _.first(food, { 'type': 'fruit' }); -### `_.flatten(array, shallow)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3347 "View in source") [Ⓣ][1] +### `_.flatten(array [, isShallow=false, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3370 "View in source") [Ⓣ][1] -Flattens a nested array *(the nesting can be to any depth)*. If `shallow` is truthy, `array` will only be flattened a single level. +Flattens a nested array *(the nesting can be to any depth)*. If `isShallow` is truthy, `array` will only be flattened a single level. If `callback` is passed, each element of `array` is passed through a callback` before flattening. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, array)*. + +If a property name is passed for `callback`, the created "_.pluck" style callback will return the property value of the given element. + +If an object is passed for `callback`, the created "_.where" style callback will return `true` for elements that have the properties of the given object, else `false`. #### Arguments 1. `array` *(Array)*: The array to compact. -2. `shallow` *(Boolean)*: A flag to indicate only flattening a single level. +2. `[isShallow=false]` *(Boolean)*: A flag to indicate only flattening a single level. +3. `[callback=identity]` *(Function|Object|String)*: The function called per iteration. If a property name or object is passed, it will be used to create a "_.pluck" or "_.where" style callback, respectively. +4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. #### Returns *(Array)*: Returns a new flattened array. @@ -328,6 +334,15 @@ _.flatten([1, [2], [3, [[4]]]]); _.flatten([1, [2], [3, [[4]]]], true); // => [1, 2, 3, [[4]]]; + +var stooges = [ + { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } +]; + +// using "_.pluck" callback shorthand +_.flatten(stooges, 'quotes'); +// => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] ``` * * * @@ -338,7 +353,7 @@ _.flatten([1, [2], [3, [[4]]]], true); ### `_.indexOf(array, value [, fromIndex=0])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3389 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3423 "View in source") [Ⓣ][1] Gets the index at which the first occurrence of `value` is found using strict equality for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` for `fromIndex` will run a faster binary search. @@ -370,7 +385,7 @@ _.indexOf([1, 1, 2, 2, 3, 3], 2, true); ### `_.initial(array [, callback|n=1, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3463 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3497 "View in source") [Ⓣ][1] Gets all but the last element of `array`. If a number `n` is passed, the last `n` elements are excluded from the result. If a `callback` function is passed, elements at the end of the array are excluded from the result as long as the `callback` returns truthy. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, array)*. @@ -427,7 +442,7 @@ _.initial(food, { 'type': 'vegetable' }); ### `_.intersection([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3497 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3531 "View in source") [Ⓣ][1] Computes the intersection of all the passed-in arrays using strict equality for comparisons, i.e. `===`. @@ -451,7 +466,7 @@ _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); ### `_.last(array [, callback|n, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3589 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3623 "View in source") [Ⓣ][1] Gets the last element of the `array`. If a number `n` is passed, the last `n` elements of the `array` are returned. If a `callback` function is passed, elements at the end of the array are returned as long as the `callback` returns truthy. The `callback` is bound to `thisArg` and invoked with three arguments;(value, index, array). @@ -508,7 +523,7 @@ _.last(food, { 'type': 'vegetable' }); ### `_.lastIndexOf(array, value [, fromIndex=array.length-1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3630 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3664 "View in source") [Ⓣ][1] Gets the index at which the last occurrence of `value` is found using strict equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the offset from the end of the collection. @@ -537,7 +552,7 @@ _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); ### `_.range([start=0], end [, step=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3671 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3705 "View in source") [Ⓣ][1] Creates an array of numbers *(positive and/or negative)* progressing from `start` up to but not including `end`. @@ -575,7 +590,7 @@ _.range(0); ### `_.rest(array [, callback|n=1, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3750 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3784 "View in source") [Ⓣ][1] The opposite of `_.initial`, this method gets all but the first value of `array`. If a number `n` is passed, the first `n` values are excluded from the result. If a `callback` function is passed, elements at the beginning of the array are excluded from the result as long as the `callback` returns truthy. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, array)*. @@ -635,7 +650,7 @@ _.rest(food, { 'type': 'fruit' }); ### `_.sortedIndex(array, value [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3814 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3848 "View in source") [Ⓣ][1] Uses a binary search to determine the smallest index at which the `value` should be inserted into `array` in order to maintain the sort order of the sorted `array`. If `callback` is passed, it will be executed for `value` and each element in `array` to compute their sort ranking. The `callback` is bound to `thisArg` and invoked with one argument; *(value)*. @@ -684,7 +699,7 @@ _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { ### `_.union([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3846 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3880 "View in source") [Ⓣ][1] Computes the union of the passed-in arrays using strict equality for comparisons, i.e. `===`. @@ -708,7 +723,7 @@ _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); ### `_.uniq(array [, isSorted=false, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3893 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3927 "View in source") [Ⓣ][1] Creates a duplicate-value-free version of the `array` using strict equality for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` for `isSorted` will run a faster algorithm. If `callback` is passed, each element of `array` is passed through a callback` before uniqueness is computed. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, array)*. @@ -755,7 +770,7 @@ _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); ### `_.without(array [, value1, value2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3952 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3986 "View in source") [Ⓣ][1] Creates an array with all occurrences of the passed values removed using strict equality for comparisons, i.e. `===`. @@ -780,7 +795,7 @@ _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); ### `_.zip([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3983 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4017 "View in source") [Ⓣ][1] Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes. For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix in a similar fashion. @@ -804,7 +819,7 @@ _.zip(['moe', 'larry'], [30, 40], [true, false]); ### `_.zipObject(keys [, values=[]])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4012 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4046 "View in source") [Ⓣ][1] Creates an object composed from arrays of `keys` and `values`. Pass either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or two arrays, one of `keys` and one of corresponding `values`. @@ -870,7 +885,7 @@ The wrapper functions `first` and `last` return wrapped values when `n` is passe ### `_.tap(value, interceptor)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4980 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L5014 "View in source") [Ⓣ][1] Invokes `interceptor` with the `value` as the first argument, and then returns `value`. The purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. @@ -900,7 +915,7 @@ _([1, 2, 3, 4]) ### `_.prototype.toString()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4997 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L5031 "View in source") [Ⓣ][1] Produces the `toString` result of the wrapped value. @@ -921,7 +936,7 @@ _([1, 2, 3]).toString(); ### `_.prototype.valueOf()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L5014 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L5048 "View in source") [Ⓣ][1] Extracts the wrapped value. @@ -1761,7 +1776,7 @@ _.where(stooges, { 'age': 40 }); ### `_.after(n, func)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4050 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4084 "View in source") [Ⓣ][1] Creates a function that is restricted to executing `func` only after it is called `n` times. The `func` is executed with the `this` binding of the created function. @@ -1789,7 +1804,7 @@ _.forEach(notes, function(note) { ### `_.bind(func [, thisArg, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4083 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4117 "View in source") [Ⓣ][1] Creates a function that, when called, invokes `func` with the `this` binding of `thisArg` and prepends any additional `bind` arguments to those passed to the bound function. @@ -1820,7 +1835,7 @@ func(); ### `_.bindAll(object [, methodName1, methodName2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4114 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4148 "View in source") [Ⓣ][1] Binds methods on `object` to `object`, overwriting the existing method. Method names may be specified as individual arguments or as arrays of method names. If no method names are provided, all the function properties of `object` will be bound. @@ -1851,7 +1866,7 @@ jQuery('#docs').on('click', view.onClick); ### `_.bindKey(object, key [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4160 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4194 "View in source") [Ⓣ][1] Creates a function that, when called, invokes the method at `object[key]` and prepends any additional `bindKey` arguments to those passed to the bound function. This method differs from `_.bind` by allowing bound functions to reference methods that will be redefined or don't yet exist. See http://michaux.ca/articles/lazy-function-definition-pattern. @@ -1892,7 +1907,7 @@ func(); ### `_.compose([func1, func2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4183 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4217 "View in source") [Ⓣ][1] Creates a function that is the composition of the passed functions, where each function consumes the return value of the function that follows. For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. Each function is executed with the `this` binding of the composed function. @@ -1919,7 +1934,7 @@ welcome('moe'); ### `_.createCallback([func=identity, thisArg, argCount=3])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4210 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4244 "View in source") [Ⓣ][1] Produces a callback bound to an optional `thisArg`. If `func` is a property name, the created callback will return the property value for a given element. If `func` is an object, the created callback will return `true` for elements that contain the equivalent object properties, otherwise it will return `false`. @@ -1939,7 +1954,7 @@ Produces a callback bound to an optional `thisArg`. If `func` is a property name ### `_.debounce(func, wait, immediate)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4276 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4310 "View in source") [Ⓣ][1] Creates a function that will delay the execution of `func` until after `wait` milliseconds have elapsed since the last time it was invoked. Pass `true` for `immediate` to cause debounce to invoke `func` on the leading, instead of the trailing, edge of the `wait` timeout. Subsequent calls to the debounced function will return the result of the last `func` call. @@ -1965,7 +1980,7 @@ jQuery(window).on('resize', lazyLayout); ### `_.defer(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4340 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4374 "View in source") [Ⓣ][1] Defers executing the `func` function until the current call stack has cleared. Additional arguments will be passed to `func` when it is invoked. @@ -1990,7 +2005,7 @@ _.defer(function() { alert('deferred'); }); ### `_.delay(func, wait [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4320 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4354 "View in source") [Ⓣ][1] Executes the `func` function after `wait` milliseconds. Additional arguments will be passed to `func` when it is invoked. @@ -2017,7 +2032,7 @@ _.delay(log, 1000, 'logged later'); ### `_.memoize(func [, resolver])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4368 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4402 "View in source") [Ⓣ][1] Creates a function that memoizes the result of `func`. If `resolver` is passed, it will be used to determine the cache key for storing the result based on the arguments passed to the memoized function. By default, the first argument passed to the memoized function is used as the cache key. The `func` is executed with the `this` binding of the memoized function. @@ -2043,7 +2058,7 @@ var fibonacci = _.memoize(function(n) { ### `_.once(func)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4395 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4429 "View in source") [Ⓣ][1] Creates a function that is restricted to execute `func` once. Repeat calls to the function will return the value of the first call. The `func` is executed with the `this` binding of the created function. @@ -2069,7 +2084,7 @@ initialize(); ### `_.partial(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4430 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4464 "View in source") [Ⓣ][1] Creates a function that, when called, invokes `func` with any additional `partial` arguments prepended to those passed to the new function. This method is similar to `_.bind`, except it does **not** alter the `this` binding. @@ -2096,7 +2111,7 @@ hi('moe'); ### `_.partialRight(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4461 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4495 "View in source") [Ⓣ][1] This method is similar to `_.partial`, except that `partial` arguments are appended to those passed to the new function. @@ -2133,7 +2148,7 @@ options.imports ### `_.throttle(func, wait)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4483 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4517 "View in source") [Ⓣ][1] Creates a function that, when executed, will only call the `func` function at most once per every `wait` milliseconds. If the throttled function is invoked more than once during the `wait` timeout, `func` will also be called on the trailing edge of the timeout. Subsequent calls to the throttled function will return the result of the last `func` call. @@ -2158,7 +2173,7 @@ jQuery(window).on('scroll', throttled); ### `_.wrap(value, wrapper)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4536 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4570 "View in source") [Ⓣ][1] Creates a function that passes `value` to the `wrapper` function as its first argument. Additional arguments passed to the function are appended to those passed to the `wrapper` function. The `wrapper` is executed with the `this` binding of the created function. @@ -3200,7 +3215,7 @@ _.values({ 'one': 1, 'two': 2, 'three': 3 }); ### `_.escape(string)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4560 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4594 "View in source") [Ⓣ][1] Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their corresponding HTML entities. @@ -3224,7 +3239,7 @@ _.escape('Moe, Larry & Curly'); ### `_.identity(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4578 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4612 "View in source") [Ⓣ][1] This function returns the first argument passed to it. @@ -3249,7 +3264,7 @@ moe === _.identity(moe); ### `_.mixin(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4604 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4638 "View in source") [Ⓣ][1] Adds functions properties of `object` to the `lodash` function and chainable wrapper. @@ -3279,7 +3294,7 @@ _('moe').capitalize(); ### `_.noConflict()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4633 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4667 "View in source") [Ⓣ][1] Reverts the '_' variable to its previous value and returns a reference to the `lodash` function. @@ -3299,7 +3314,7 @@ var lodash = _.noConflict(); ### `_.random([min=0, max=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4656 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4690 "View in source") [Ⓣ][1] Produces a random number between `min` and `max` *(inclusive)*. If only one argument is passed, a number between `0` and the given number will be returned. @@ -3327,7 +3342,7 @@ _.random(5); ### `_.result(object, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4694 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4728 "View in source") [Ⓣ][1] Resolves the value of `property` on `object`. If `property` is a function, it will be invoked and its result returned, else the property value is returned. If `object` is falsey, then `null` is returned. @@ -3380,7 +3395,7 @@ Create a new `lodash` function using the given `context` object. ### `_.template(text, data, options)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4781 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4815 "View in source") [Ⓣ][1] A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. @@ -3464,7 +3479,7 @@ fs.writeFileSync(path.join(cwd, 'jst.js'), '\ ### `_.times(n, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4906 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4940 "View in source") [Ⓣ][1] Executes the `callback` function `n` times, returning an array of the results of each `callback` execution. The `callback` is bound to `thisArg` and invoked with one argument; *(index)*. @@ -3496,7 +3511,7 @@ _.times(3, function(n) { this.cast(n); }, mage); ### `_.unescape(string)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4932 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4966 "View in source") [Ⓣ][1] The opposite of `_.escape`, this method converts the HTML entities `&`, `<`, `>`, `"`, and `'` in `string` to their corresponding characters. @@ -3520,7 +3535,7 @@ _.unescape('Moe, Larry & Curly'); ### `_.uniqueId([prefix])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4952 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4986 "View in source") [Ⓣ][1] Generates a unique ID. If `prefix` is passed, the ID will be appended to it. @@ -3573,7 +3588,7 @@ A reference to the `lodash` function. ### `_.VERSION` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L5186 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L5220 "View in source") [Ⓣ][1] *(String)*: The semantic version number. diff --git a/lodash.js b/lodash.js index 6b1c956ce..bf68a71eb 100644 --- a/lodash.js +++ b/lodash.js @@ -3327,14 +3327,28 @@ } /** - * Flattens a nested array (the nesting can be to any depth). If `shallow` is - * truthy, `array` will only be flattened a single level. + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truthy, `array` will only be flattened a single level. If `callback` + * is passed, each element of `array` is passed through a callback` before + * flattening. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. - * @param {Boolean} shallow A flag to indicate only flattening a single level. + * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * @@ -3343,18 +3357,38 @@ * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; + * + * var stooges = [ + * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(stooges, 'quotes'); + * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ - function flatten(array, shallow) { + function flatten(array, isShallow, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = isShallow; + isShallow = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg); + } while (++index < length) { var value = array[index]; - + if (callback) { + value = callback(value, index, array); + } // recursively flatten arrays (susceptible to call stack limits) if (isArray(value)) { - push.apply(result, shallow ? value : flatten(value)); + push.apply(result, isShallow ? value : flatten(value)); } else { result.push(value); } diff --git a/test/test-build.js b/test/test-build.js index c1837e048..dec90fa56 100644 --- a/test/test-build.js +++ b/test/test-build.js @@ -821,8 +821,7 @@ var start = _.after(2, _.once(QUnit.start)); build(['-s', 'underscore'], function(data) { - var last, - array = [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }], + var array = [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }], basename = path.basename(data.outputPath, '.js'), context = createContext(); @@ -869,6 +868,7 @@ equal(actual, _.first(array), '_.find: ' + basename); + var last; actual = lodash.forEach(array, function(value) { last = value; return false; @@ -877,6 +877,15 @@ equal(last, _.last(array), '_.forEach should not exit early: ' + basename); equal(actual, undefined, '_.forEach should return `undefined`: ' + basename); + array = [{ 'a': [1, 2] }, { 'a': [3] }]; + + actual = lodash.flatten(array, function(value, index) { + return this[index].a; + }, array); + + deepEqual(actual, array, '_.flatten should should ignore `callback` and `thisArg`: ' + basename); + deepEqual(lodash.flatten(array, 'a'), array, '_.flatten should should ignore string `callback` values: ' + basename); + object = { 'length': 0, 'splice': Array.prototype.splice }; equal(lodash.isEmpty(object), false, '_.isEmpty should return `false` for jQuery/MooTools DOM query collections: ' + basename); diff --git a/test/test.js b/test/test.js index 22cd5d201..85d9837ac 100644 --- a/test/test.js +++ b/test/test.js @@ -789,6 +789,46 @@ QUnit.module('lodash.flatten'); (function() { + var array = [{ 'a': [1, [2]] }, { 'a': [3] }]; + + test('should work with a `callback`', function() { + var actual = _.flatten(array, function(value) { + return value.a; + }); + + deepEqual(actual, [1, 2, 3]); + }); + + test('should work with `isShallow` and `callback`', function() { + var actual = _.flatten(array, true, function(value) { + return value.a; + }); + + deepEqual(actual, [1, [2], 3]); + }); + + test('should pass the correct `callback` arguments', function() { + var args; + + _.flatten(array, function() { + args || (args = slice.call(arguments)); + }); + + deepEqual(args, [{ 'a': [1, [2]] }, 0, array]); + }); + + test('supports the `thisArg` argument', function() { + var actual = _.flatten(array, function(value, index) { + return this[index].a; + }, array); + + deepEqual(actual, [1, 2, 3]); + }); + + test('should work with a string for `callback`', function() { + deepEqual(_.flatten(array, 'a'), [1, 2, 3]); + }); + test('should treat sparse arrays as dense', function() { var array = [[1, 2, 3], Array(3)], expected = [1, 2, 3],