Skip to content

Instantly share code, notes, and snippets.

@bigs
Last active August 29, 2015 13:56
Show Gist options
  • Save bigs/9103441 to your computer and use it in GitHub Desktop.
Save bigs/9103441 to your computer and use it in GitHub Desktop.
lambda functions in javascript
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