Skip to content

Instantly share code, notes, and snippets.

@tvandervossen
Created November 4, 2010 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvandervossen/662284 to your computer and use it in GitHub Desktop.
Save tvandervossen/662284 to your computer and use it in GitHub Desktop.
List comprehension for JavaScript
Object.prototype.collect = function(callback) {
var result = [];
for (var key in this) {
if (this.hasOwnProperty(key)) {
result.push(callback(this[key], key));
}
}
return result;
};
> ['one', 'two'].collect(function(x) { return x.toUpperCase() })
["ONE", "TWO"]
> ['one', 'two'].collect(function(x, i) { return i+': '+x })
["0: one", "1: two"]
> {'name': 'Thijs van der Vossen', 'twitter': '@thijs' }.collect(function(v, k) { return k+': '+v })
["name: Thijs van der Vossen", "twitter: @thijs"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment