Permalink
Browse files

Implement union.

  • Loading branch information...
1 parent bd3aef1 commit 0fb89d1b8da5f5429362aa1f12a8737ae0794da4 @Gozala committed Jan 3, 2013
Showing with 53 additions and 0 deletions.
  1. +1 −0 index.js
  2. +3 −0 test/index.js
  3. +34 −0 test/union.js
  4. +15 −0 union.js
View
1 index.js
@@ -1,2 +1,3 @@
"use strict";
+exports.union = require("./union")
View
3 test/index.js
@@ -0,0 +1,3 @@
+"use strict";
+
+exports["test union"] = require("./union")
View
34 test/union.js
@@ -0,0 +1,34 @@
+"use strict";
+
+var union = require("../union")
+
+exports["test empty"] = function(assert) {
+ assert.deepEqual(union(), [], "calling union without args return []")
+}
+
+exports["test one set"] = function(assert) {
+ assert.deepEqual(union([1, 2]), [1, 2],
+ "calling union with one array returns identical array")
+}
+
+exports["test union of two sets"] = function(assert) {
+ assert.deepEqual(union([1, 2], [3, 4]), [1, 2, 3, 4],
+ "union contains elements from both sets")
+ assert.deepEqual(union([1, 2], [2, 3]), [1, 2, 3],
+ "union does not repeats common elements")
+}
+
+exports["test union of 2+ sets"] = function(assert) {
+ assert.deepEqual(union([1, 2], [2, 3], [3, 4]),
+ [1, 2, 3, 4],
+ "common elements don't repeat")
+
+ assert.deepEqual(union([1, 2, 3],
+ [4, 5, 1],
+ [5],
+ [6, 7, 3, 1],
+ [2, 8, 3],
+ [9, 0]),
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
+ "common elements don't repeat regardless of number of sets")
+}
View
15 union.js
@@ -0,0 +1,15 @@
+"use strict";
+var slicer = Array.prototype.slice
+
+function add(union, item) {
+ if (union.indexOf(item) < 0) union.push(item)
+ return union
+}
+
+function include(union, set) {
+ return set.reduce(add, union)
+}
+
+module.exports = function union() {
+ return slicer.call(arguments).reduce(include, [])
+}

0 comments on commit 0fb89d1

Please sign in to comment.