Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Created February 21, 2010 17:18
Show Gist options
  • Select an option

  • Save choonkeat/310418 to your computer and use it in GitHub Desktop.

Select an option

Save choonkeat/310418 to your computer and use it in GitHub Desktop.
(function(array_plus) {
function x_flatten(array, sum) {
sum = sum || [];
var y;
for (var x = array.length-1; x >= 0; x--) {
y = array[x];
if ((typeof y) == "object" && y.length) {
x_flatten(y, sum);
} else {
sum.unshift(y);
}
}
return sum;
}
function x_intersect(array1, array2) {
var y, sum, seen;
sum = [];
seen = {};
if (array1.length > array2.length) {
y = array1;
array1 = array2
array2 = y;
}
for (var x = array2.length-1; x >= 0; x--) {
y = array1[x];
if (y) seen[y] = (seen[y] || 0) + 1;
y = array2[x];
if (y) seen[y] = (seen[y] || 0) + 1;
}
for (y in seen) {
if (seen[y] > 1) sum.push(y);
}
return sum;
}
function x_unique(array) {
var sum = [], seen = {}, y;
for (var x = array.length-1; x >= 0; x--) {
y = array[x];
if (! seen[y]) {
seen[y] = true;
sum.push(y)
}
}
return sum;
}
array_plus.flatten = x_flatten;
array_plus.intersect = x_intersect;
array_plus.unique = x_unique;
})(window.array_plus = {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment