Permalink
Browse files

hoisting out the flatten function.

  • Loading branch information...
1 parent 94f10d8 commit 0da7b393b08c2459bc302f4ccb6401587b1fb1da @jashkenas committed May 23, 2012
Showing with 16 additions and 13 deletions.
  1. +16 −13 underscore.js
View
@@ -359,18 +359,21 @@
return _.filter(array, function(value){ return !!value; });
};
+ // Internal implementation of a recursive `flatten` function.
+ var flatten = function(input, shallow, output) {
+ each(input, function(value) {
+ if (_.isArray(value)) {
+ shallow ? push.apply(output, value) : flatten(value, shallow, output);
+ } else {
+ output.push(value);
+ }
+ });
+ return output;
+ };
+
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
- return (function flatten(input, output) {
- each(input, function(value) {
- if (_.isArray(value)) {
- shallow ? push.apply(output, value) : flatten(value, output);
- } else {
- output.push(value);
- }
- });
- return output;
- })(array, []);
+ return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
@@ -397,7 +400,7 @@
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
- return _.uniq(_.flatten(arguments, true));
+ return _.uniq(flatten(arguments, true, []));
};
// Produce an array that contains every item shared between all the
@@ -414,7 +417,7 @@
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
- var rest = _.flatten(slice.call(arguments, 1), true);
+ var rest = flatten(slice.call(arguments, 1), true, []);
return _.filter(array, function(value){ return !_.include(rest, value); });
};
@@ -671,7 +674,7 @@
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var result = {};
- each(_.flatten(slice.call(arguments, 1)), function(key) {
+ each(flatten(slice.call(arguments, 1), true, []), function(key) {
if (key in obj) result[key] = obj[key];
});
return result;

0 comments on commit 0da7b39

Please sign in to comment.