Skip to content

Instantly share code, notes, and snippets.

@rizkyabdilah
Created May 1, 2012 13:40
Show Gist options
  • Save rizkyabdilah/2567986 to your computer and use it in GitHub Desktop.
Save rizkyabdilah/2567986 to your computer and use it in GitHub Desktop.
Simple array intersect function in coffeescript
arrayIntersect_ = (arg1, arg2) ->
retVal = []
hashMap = {}
for l in arg1
hashMap[l] = 1
for l in arg2
if hashMap[l] and ((hashMap[l] += 1) == 2)
retVal.push(l)
return retVal
arrayIntersect = (arg1, arg2) ->
## init iterate menggunakan list yang lebih kecil
if arg1.length <= arg2.length
return arrayIntersect_(arg1, arg2)
return arrayIntersect_(arg2, arg1)
## example
arrayIntersect(['a', 'b'], ['b'])
// compiled from coffeescript into javacript
var arrayIntersect, arrayIntersect_;
arrayIntersect_ = function(arg1, arg2) {
var hashMap, l, retVal, _i, _j, _len, _len2;
retVal = [];
hashMap = {};
for (_i = 0, _len = arg1.length; _i < _len; _i++) {
l = arg1[_i];
hashMap[l] = 1;
}
for (_j = 0, _len2 = arg2.length; _j < _len2; _j++) {
l = arg2[_j];
if (hashMap[l] && ((hashMap[l] += 1) === 2)) retVal.push(l);
}
return retVal;
};
arrayIntersect = function(arg1, arg2) {
if (arg1.length <= arg2.length) return arrayIntersect_(arg1, arg2);
return arrayIntersect_(arg2, arg1);
};
arrayIntersect(['a', 'b'], ['b']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment