Skip to content

Commit

Permalink
Issue jashkenas#309, adding symmetric difference as _.symDifference, …
Browse files Browse the repository at this point in the history
…and making _.difference accept any number of arguments.
  • Loading branch information
jashkenas committed Nov 23, 2011
1 parent 65ab040 commit 7653c5f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 8 additions & 0 deletions test/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,14 @@ $(document).ready(function() {
test("arrays: difference", function() {
var result = _.difference([1, 2, 3], [2, 30, 40]);
equals(result.join(' '), '1 3', 'takes the difference of two arrays');

var result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
equals(result.join(' '), '3 4', 'takes the difference of three arrays');
});

test("arrays: symDifference", function() {
var result = _.symDifference([1, 2, 3], [2, 22, 222], [3, 33, 333], [222, 333, 444], [5]);
equals(result.join(' '), '1 22 33 444 5', 'takes the symmetric difference');
});

test('arrays: zip', function() {
Expand Down
15 changes: 12 additions & 3 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,19 @@
});
};

// Take the difference between one array and another.
// 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, other) {
return _.filter(array, function(value){ return !_.include(other, value); });
_.difference = function(array) {
var rest = _.flatten(slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.include(rest, value); });
};

// Take the symmetric difference between a list of arrays. Only the elements
// present in one of the input arrays will remain.
_.symDifference = function() {
return _.reduce(arguments, function(memo, array) {
return _.union(_.difference(memo, array), _.difference(array, memo));
});
};

// Zip together multiple lists into a single array -- elements that share
Expand Down

0 comments on commit 7653c5f

Please sign in to comment.