Skip to content

Commit

Permalink
hoisting out the flatten function.
Browse files Browse the repository at this point in the history
  • Loading branch information
jashkenas committed May 23, 2012
1 parent 94f10d8 commit 0da7b39
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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
Expand All @@ -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); });
};

Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 0da7b39

Please sign in to comment.