Commit ca8fa98a authored by Chris's avatar Chris

Adding a getIntersection() method to BasicSet object

parent c46abd9e
......@@ -116,6 +116,18 @@ BasicSet.prototype.getAll = function() {
return results;
};
BasicSet.prototype.getIntersection = function(otherSet) {
if (!Array.isArray(otherSet)) { return []; }
var i, j, key, results = [];
for (i = 0, len = otherSet.length; i < len; i++) {
if (this._data[otherSet[i]] !== undefined) {
results.push(otherSet[i]);
}
}
return results;
};
/**
* Returns the number of elements in the set.
*
......
......@@ -264,6 +264,26 @@ test('getAll()', function() {
deepEqual(set.getAll(), ['a','b','c','d','e'], "{'a','b','c','d','e'}.getAll() -> ['a','b','c','d','e']");
});
test('getIntersection()', function() {
// Test numbers
var set = new BasicSet(1,2,3,4,5);
deepEqual(set.getIntersection([1,2,3,4,5]), [1,2,3,4,5], '{1,2,3,4,5}.getIntersection([1,2,3,4,5]) -> [1,2,3,4,5]');
deepEqual(set.getIntersection([]), [], '{1,2,3,4,5}.getIntersection([]) -> []');
deepEqual(set.getIntersection([1,2,4]), [1,2,4], '{1,2,3,4,5}.getIntersection([1,2,4]) -> [1,2,4]');
deepEqual(set.getIntersection([1,2,4,8,16]), [1,2,4], '{1,2,3,4,5}.getIntersection([1,2,4,8,16]) -> [1,2,4]');
// Test strings
set = new BasicSet('a','b','c','d','e');
deepEqual(set.getIntersection(['a','b','c','d','e']), ['a','b','c','d','e'], "{'a','b','c','d','e'}.getIntersection(['a','b','d']) -> ['a','b','d']");
deepEqual(set.getIntersection([]), [], "{'a','b','c','d','e'}.getIntersection([]) -> []");
deepEqual(set.getIntersection(['a','b','d']), ['a','b','d'], "{'a','b','c','d','e'}.getIntersection(['a','b','d']) -> ['a','b','d']");
deepEqual(set.getIntersection(['a','b','d','h','p']), ['a','b','d'], "{'a','b','c','d','e'}.getIntersection(['a','b','d','h','p']) -> ['a','b','d']");
// Test mixed numbers and strings
set = new BasicSet(1,2,3,4,5);
deepEqual(set.getIntersection(['1',2,'4']), ['1',2,'4'], "{1,2,3,4,5}.getIntersection(['1',2,'4']) -> ['1',2,'4']");
});
test('size()', function() {
var set = new BasicSet(1,2,3);
ok(set.size() === 3, '{1,2,3}.size() === 3');
......
......@@ -39,6 +39,9 @@ var set = new BasicSet(1,'2',[2.5,'c'],'d',5.0); // {1,'2',2.5,'c','d',5.0}
**getAll()**
<br>Returns an `Array` containing every element in the `BasicSet` object.
**getIntersection(valuesArray)**
<br>Returns an `Array` containing every element from `valuesArray` that is present in the `BasicSet` object. `valuesArray` must be an array of values.
**size()**
<br>Returns the number of elements in the `BasicSet` object.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment