Skip to content

Instantly share code, notes, and snippets.

@bripkens
Created December 19, 2012 19:26
Show Gist options
  • Save bripkens/4339689 to your computer and use it in GitHub Desktop.
Save bripkens/4339689 to your computer and use it in GitHub Desktop.
Functional programming in JavaScript example with Lo-Dash
<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>
/*
* 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", "tom.mason@example.com", "History professor"),
new Person("Sheldon Cooper", "sheldon.cooper@example.com", "Theoretical physicist"),
new Person("Luke Skywalker", "luke.skywalker@example.com", "Saviour of the universe"),
new Person("Barney Stinson", "barney.stinson@example.com", "?")
];
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