mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-12 20:07:49 +00:00
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:
@@ -50,10 +50,13 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
test("arrays: flatten", function() {
|
||||
var list = [1, [2], [3, [[[4]]]]];
|
||||
equals(_.flatten(list).join(', '), '1, 2, 3, 4', 'can flatten nested arrays');
|
||||
var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]);
|
||||
equals(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
|
||||
if (window.JSON) {
|
||||
var list = [1, [2], [3, [[[4]]]]];
|
||||
equals(JSON.stringify(_.flatten(list)), '[1,2,3,4]', 'can flatten nested arrays');
|
||||
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() {
|
||||
@@ -97,6 +100,9 @@ $(document).ready(function() {
|
||||
test("arrays: union", function() {
|
||||
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');
|
||||
|
||||
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() {
|
||||
|
||||
@@ -345,9 +345,9 @@
|
||||
};
|
||||
|
||||
// Return a completely flattened version of an array.
|
||||
_.flatten = function(array) {
|
||||
_.flatten = function(array, shallow) {
|
||||
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;
|
||||
return memo;
|
||||
}, []);
|
||||
@@ -377,7 +377,7 @@
|
||||
// Produce an array that contains the union: each distinct element from all of
|
||||
// the passed-in arrays.
|
||||
_.union = function() {
|
||||
return _.uniq(_.flatten(arguments));
|
||||
return _.uniq(_.flatten(arguments, true));
|
||||
};
|
||||
|
||||
// Produce an array that contains every item shared between all the
|
||||
|
||||
Reference in New Issue
Block a user