Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Last active December 15, 2015 10:29
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 jnicklas/5246111 to your computer and use it in GitHub Desktop.
Save jnicklas/5246111 to your computer and use it in GitHub Desktop.
Functional JS stuff
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);
};
};
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"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment