public
Last active

Functional JS stuff

  • Download Gist
funcs.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12
function get(prop) {
return function(object) {
return object[prop];
};
};
 
function call(prop) {
var args = Array.prototype.slice.call(arguments, 1);
return function(object) {
return object[prop].apply(object, args);
};
};
usage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
var jonas = { name: "Jonas" };
 
get("name")(jonas); // => "Jonas"
 
var jonas = {
title: "Mr.",
first: "Jonas",
last: "Nicklas",
fullName: function(withTitle) {
if(withTitle) {
return this.title + " " + this.first + " " + this.last;
} else {
return this.first + " " + this.last;
}
}
};
 
call("fullName")(jonas); // => "Jonas Nicklas"
call("fullName", true)(jonas); // => "Mr. Jonas Nicklas"
 
var people = [{ name: "Jonas" }, { name: "Kim" }];
 
people.map(function(person) { return person.name }); // => ["Jonas", "Kim"]
people.map(get("name")); // => ["Jonas", "Kim"]
 
var people = [jonas];
 
people.map(function(person) { return person.fullName(true) }); // => ["Mr Jonas Nicklas"]
people.map(call("fullName", true)); // => ["Mr Jonas Nicklas"]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.