Fixes #341, flattening arrays in the context of taking a union shouldn't be deep. Adding a shallow parameter to _.flatten()

This commit is contained in:
Jeremy Ashkenas
2011-10-19 15:59:53 -04:00
parent 3587febd8e
commit 4b2de2e107
2 changed files with 13 additions and 7 deletions

View File

@@ -50,10 +50,13 @@ $(document).ready(function() {
}); });
test("arrays: flatten", function() { test("arrays: flatten", function() {
var list = [1, [2], [3, [[[4]]]]]; if (window.JSON) {
equals(_.flatten(list).join(', '), '1, 2, 3, 4', 'can flatten nested arrays'); var list = [1, [2], [3, [[[4]]]]];
var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]); equals(JSON.stringify(_.flatten(list)), '[1,2,3,4]', 'can flatten nested arrays');
equals(result.join(', '), '1, 2, 3, 4', 'works on an arguments object'); equals(JSON.stringify(_.flatten(list, true)), '[1,2,3,[[[4]]]]', 'can shallowly flatten nested arrays');
var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]);
equals(JSON.stringify(result), '[1,2,3,4]', 'works on an arguments object');
}
}); });
test("arrays: without", function() { test("arrays: without", function() {
@@ -97,6 +100,9 @@ $(document).ready(function() {
test("arrays: union", function() { test("arrays: union", function() {
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]); var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);
equals(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays'); equals(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays');
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
equals(result.join(' '), '1 2 3 30 40 1', 'takes the union of a list of nested arrays');
}); });
test("arrays: difference", function() { test("arrays: difference", function() {

View File

@@ -345,9 +345,9 @@
}; };
// Return a completely flattened version of an array. // Return a completely flattened version of an array.
_.flatten = function(array) { _.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) { return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value)); if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value; memo[memo.length] = value;
return memo; return memo;
}, []); }, []);
@@ -377,7 +377,7 @@
// Produce an array that contains the union: each distinct element from all of // Produce an array that contains the union: each distinct element from all of
// the passed-in arrays. // the passed-in arrays.
_.union = function() { _.union = function() {
return _.uniq(_.flatten(arguments)); return _.uniq(_.flatten(arguments, true));
}; };
// Produce an array that contains every item shared between all the // Produce an array that contains every item shared between all the