Skip to content

Commit d7087a6

Browse files
committed
speed up Lib.difference
1 parent bbd63d4 commit d7087a6

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

src/lib/set_operations.js

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,33 @@
99
'use strict';
1010

1111

12-
/*
12+
/**
1313
* Computes the set difference of two arrays.
1414
*
1515
* @param {array} a
1616
* @param {array} b
17-
* @returns all elements of a that are not in b.
17+
* @returns out all elements of a that are not in b.
1818
* If a is not an array, an empty array is returned.
1919
* If b is not an array, a is returned.
2020
*/
2121
function difference(a, b) {
22-
if(!Array.isArray(a)) {
23-
return [];
22+
if(!Array.isArray(a)) return [];
23+
if(!Array.isArray(b)) return a;
24+
25+
var hash = {};
26+
var out = [];
27+
var i;
28+
29+
for(i = 0; i < b.length; i++) {
30+
hash[b[i]] = 1;
2431
}
25-
if(!Array.isArray(b)) {
26-
return a;
32+
33+
for(i = 0; i < a.length; i++) {
34+
var ai = a[i];
35+
if(!hash[ai]) out.push(ai);
2736
}
28-
return a.filter(function(e) {
29-
return b.indexOf(e) < 0;
30-
});
37+
38+
return out;
3139
}
3240

3341
module.exports = {

0 commit comments

Comments
 (0)