Created
May 24, 2012 09:14
-
-
Save ForbesLindesay/2780415 to your computer and use it in GitHub Desktop.
contains, distinct, group by, select many
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.contains = function(value, comparison){ | |
comparison = comparison || function(A,B){ | |
return (A === B); | |
}; | |
return this.some(function(item){ | |
return comparison(item, value); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function distinct(arr, comparison){ | |
var acc = []; | |
for(var i = 0; i<arr.length; i++){ | |
if(!acc.contains(arr[i], comparison)){ | |
acc.push(arr[i]); | |
} | |
} | |
return acc; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.distinct = function(comparison){ | |
if(comparison) return distinct(this, comparison); | |
var set = {}; | |
var acc = []; | |
for(var i = 0; i<arr.length; i++){ | |
if(!set[arr[i]]){ | |
set[arr[i]] = true; | |
acc.push(arr[i]); | |
} | |
} | |
return acc; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function flatten(array){ | |
if(typeof array.selectMany === 'function'){ | |
return array.selectMany(flatten); | |
} else { | |
return [array]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.selectMany = function(selector){ | |
selector = selector || function(value){return value;}; | |
var acc = []; | |
var mapped = this.map(selector); | |
for(var i = 0; i<mapped.length; i++){ | |
for(var j = 0; j<mapped[i].length; j++){ | |
acc.push(mapped[i][j]); | |
} | |
} | |
return acc; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment