# Gozala/interset

Implement difference.

Gozala committed Jan 3, 2013
1 parent 0fb89d1 commit 44049ce5d03dd05c6e719572caf80d3eba80b167
Showing with 53 additions and 0 deletions.
1. +11 −0 difference.js
2. +1 −0 index.js
3. +40 −0 test/difference.js
4. +1 −0 test/index.js
 @@ -0,0 +1,11 @@ +"use strict"; + +var slicer = Array.prototype.slice +var concater = Array.prototype.concat +var excludes = function excludes(item) { return this.indexOf(item) < 0 } + +module.exports = function difference(source, exclude) { + if (!source) throw TypeError("difference requires at least two arguments") + exclude = concater.apply([], slicer.call(arguments, 1)) + return source.filter(excludes, exclude) +}
 @@ -1,3 +1,4 @@ "use strict"; exports.union = require("./union") +exports.difference = require("./difference")
 @@ -0,0 +1,40 @@ +"use strict"; + +var difference = require("../difference") + +exports["test empty"] = function(assert) { + assert.throws(function() { + difference() + }, "calling difference without args throws") +} + +exports["test difference on single set"] = function(assert) { + assert.deepEqual(difference([1, 2]), [1, 2], + "difference between set nothing is a same set") +} + +exports["test difference of two sets"] = function(assert) { + assert.deepEqual(difference([1, 2], [3, 4]), [1, 2], + "difference between non overlaping a and b is a") + assert.deepEqual(difference([1, 2], [2, 3]), [1], + "difference excludes items from 1st set if contained by 2nd") +} + +exports["test difference of 2+ sets"] = function(assert) { + assert.deepEqual(difference([1, 2, 3, 4, 5, 6], + [2, 4, 7], + [3, 4], + [4, 5], + [5]), + [1, 6], + "repeating elements are excluded from 1st") + + + assert.deepEqual(difference([1, 2, 3, 4, 5, 6], + [8, 9, 0], + [7, 0], + [11, 15], + [9]), + [1, 2, 3, 4, 5, 6], + "result is identical of 1st set if items don't repeat") +}
 @@ -1,3 +1,4 @@ "use strict"; exports["test union"] = require("./union") +exports["test difference"] = require("./difference")