Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Implement difference.

  • Loading branch information...
commit 44049ce5d03dd05c6e719572caf80d3eba80b167 1 parent 0fb89d1
@Gozala authored
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
View
11 difference.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)
+}
View
1  index.js
@@ -1,3 +1,4 @@
"use strict";
exports.union = require("./union")
+exports.difference = require("./difference")
View
40 test/difference.js
@@ -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")
+}
View
1  test/index.js
@@ -1,3 +1,4 @@
"use strict";
exports["test union"] = require("./union")
+exports["test difference"] = require("./difference")
Please sign in to comment.
Something went wrong with that request. Please try again.