Created
December 19, 2012 19:26
-
-
Save bripkens/4339689 to your computer and use it in GitHub Desktop.
Functional programming in JavaScript example with Lo-Dash
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
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.0-rc.3/lodash.js"></script> | |
<table id="people"> | |
<thead> | |
<tr> | |
<th>Id</th> | |
<th>Name</th> | |
<th>Email</th> | |
<th>Occupation</th> | |
</tr> | |
</thead> | |
<tbody> | |
</tbody> | |
</table> |
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
/* | |
* Just some data that we may have gotten from a web service | |
*/ | |
var Person = function Person(name, email, occupation) { | |
this.id = _.uniqueId(); | |
this.name = name; | |
this.email = email; | |
this.occupation = occupation; | |
}; | |
var data = [ | |
new Person("Tom Mason", "[email protected]", "History professor"), | |
new Person("Sheldon Cooper", "[email protected]", "Theoretical physicist"), | |
new Person("Luke Skywalker", "[email protected]", "Saviour of the universe"), | |
new Person("Barney Stinson", "[email protected]", "?") | |
]; | |
var output = document.body.querySelector("#people tbody"); | |
/* | |
* Some functions that will help us program in a functional way | |
*/ | |
var propOf = function(obj) { | |
return function(name) { | |
return obj[name]; | |
}; | |
}; | |
var append = function(parent, child) { | |
parent.appendChild(child); | |
return parent; | |
}; | |
var createTextNode = _.bind(document.createTextNode, document); | |
var wrap = function(elementType) { | |
return function(child) { | |
var parent = document.createElement(elementType); | |
parent.appendChild(child); | |
return parent; | |
}; | |
}; | |
/* | |
* Actual implementation in a functional style | |
*/ | |
_(data).map(function(person) { | |
return _(["id", "name", "email", "occupation"]) | |
.map(propOf(person)) | |
.map(createTextNode) | |
.map(wrap('td')) | |
.reduce(append, document.createElement("tr")); | |
}).reduce(append, output); | |
/* | |
* The same solution with ECMAScript 5 | |
*/ | |
data.forEach(function(person) { | |
var row = document.createElement("tr"); | |
["id", "name", "email", "occupation"].forEach(function(prop) { | |
var text = document.createTextNode(person[prop]); | |
var td = document.createElement("td"); | |
td.appendChild(text); | |
row.appendChild(td); | |
}); | |
output.appendChild(row); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment