Last active
August 29, 2015 13:56
-
-
Save bigs/9103441 to your computer and use it in GitHub Desktop.
lambda functions in 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
var lambda = function (str) { | |
var res = str.match(/^\s*([a-z]+(?:\s+[a-z]+)*)\s*\->\s*(.+?)\s*$/); | |
if (!res) { | |
throw new Error('Invalid lambda expression'); | |
} | |
var args = res[1].replace(/\s{2,}/g, ' ').split(' ') | |
, body = 'return ' + res[2] + ';'; | |
return new Function(args, body); | |
}; | |
var data = [ | |
{name: 'Bill', age: 30}, | |
{name: 'Susan', age: 29} | |
]; | |
var names = data.map(lambda("x -> x.name")); // ['Bill', 'Susan'] | |
var totalAge = data.reduce(lambda("m x -> m + x.age"), 0); // 59 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment