Permalink
Browse files

Implement intersection.

  • Loading branch information...
Gozala committed Jan 3, 2013
1 parent 44049ce commit 1408d22ac59fab0384c770f4cdb19f5d00eca773
Showing with 54 additions and 0 deletions.
  1. +1 −0 index.js
  2. +16 −0 intersection.js
  3. +1 −0 test/index.js
  4. +36 −0 test/intersection.js
View
@@ -2,3 +2,4 @@
exports.union = require("./union")
exports.difference = require("./difference")
+exports.intersection = require("./intersection")
View
@@ -0,0 +1,16 @@
+"use strict";
+
+var slicer = Array.prototype.slice
+var contains = function(item) { return this.indexOf(item) >= 0 }
+
+function intersection2(first, second) {
+ return first.length > second.length ? first.filter(contains, second) :
+ second.filter(contains, first)
+}
+
+module.exports = function intersection(first, second, rest) {
+ if (!first) throw TypeError("intersection requires at least one arguments")
+ if (!second) return first
+ if (!rest) return intersection2(first, second)
+ return slicer.call(arguments, 1).reduce(intersection2, first)
+}
View
@@ -2,3 +2,4 @@
exports["test union"] = require("./union")
exports["test difference"] = require("./difference")
+exports["test intersection"] = require("./intersection")
View
@@ -0,0 +1,36 @@
+"use strict";
+
+var intersection = require("../intersection")
+
+exports["test no args"] = function(assert) {
+ assert.throws(function() {
+ intersection()
+ }, "calling intersection without args throws")
+}
+
+exports["test one set"] = function(assert) {
+ assert.deepEqual(intersection([1, 2]), [1, 2],
+ "calling intersection with one set returns identical")
+}
+
+exports["test intersection of two sets"] = function(assert) {
+ assert.deepEqual(intersection([1, 2], [3, 4]), [],
+ "intersection is empty if no common items found")
+ assert.deepEqual(intersection([1, 2], [2, 3]), [2],
+ "intersection returns only common items")
+}
+
+exports["test intersection of 2+ sets"] = function(assert) {
+ assert.deepEqual(intersection([1, 2], [2, 3], [3, 4]),
+ [],
+ "intersection is empty if there are no common elements")
+
+ assert.deepEqual(intersection([1, 2, 3, 4, 5, 7],
+ [4, 5, 1, 9, 0, 7],
+ [1, 5, 7],
+ [6, 7, 3, 1],
+ [2, 8, 7, 1, 3],
+ [7, 8, 9, 0, 1]).sort(),
+ [1, 7].sort(),
+ "contains only common items of all sets")
+}

0 comments on commit 1408d22

Please sign in to comment.