diff --git a/set.js b/set.js index a0ed7a96..231d5bc1 100644 --- a/set.js +++ b/set.js @@ -109,3 +109,33 @@ exports.difference = function(A, B) { return D; }; + +/** + * Function computing the symmetric difference between two sets. + * + * @param {Set} A - First set. + * @param {Set} B - Second set. + * @return {Set} - The symmetric difference. + */ +exports.symmetricDifference = function(A, B) { + var S = new Set(); + + var iterator = A.values(), + step; + + while ((step = iterator.next(), !step.done)) { + if (!B.has(step.value)) + S.add(step.value); + } + + iterator = B.values(); + + while ((step = iterator.next(), !step.done)) { + if (!A.has(step.value)) + S.add(step.value); + } + + return S; +}; + +// TODO: subset, superset, in-place diff --git a/test/set.js b/test/set.js index 5bd4500a..c9cedade 100644 --- a/test/set.js +++ b/test/set.js @@ -65,4 +65,16 @@ describe('Set functions', function() { assert.deepEqual(Array.from(D), [1, 4, 5]); }); }); + + describe('#.symmetricDifference', function() { + + it('should properly compute the symmetric difference of two sets.', function() { + var A = new Set([1, 2, 3]), + B = new Set([3, 4, 5]); + + var S = functions.symmetricDifference(A, B); + + assert.deepEqual(Array.from(S), [1, 2, 4, 5]); + }); + }); });