Created
November 4, 2010 09:46
-
-
Save tvandervossen/662284 to your computer and use it in GitHub Desktop.
List comprehension for JavaScript
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
Object.prototype.collect = function(callback) { | |
var result = []; | |
for (var key in this) { | |
if (this.hasOwnProperty(key)) { | |
result.push(callback(this[key], key)); | |
} | |
} | |
return result; | |
}; |
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
> ['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