From 7653c5fe09f3cd6929698ca6dea5deb7bc0b537b Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Wed, 23 Nov 2011 12:42:22 -0500 Subject: [PATCH] Issue #309, adding symmetric difference as _.symDifference, and making _.difference accept any number of arguments. --- test/arrays.js | 8 ++++++++ underscore.js | 15 ++++++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/test/arrays.js b/test/arrays.js index ae00faf0a..1c910355f 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -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() { diff --git a/underscore.js b/underscore.js index 6574cccfa..6c9492ace 100644 --- a/underscore.js +++ b/underscore.js @@ -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