Last active
December 15, 2015 10:29
-
-
Save jnicklas/5246111 to your computer and use it in GitHub Desktop.
Functional JS stuff
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
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); | |
}; | |
}; |
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 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