Last active
June 15, 2016 14:19
-
-
Save gor181/3fb05ee804ddb61942397c611db8c680 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//Example of underscore chaining | |
var users = [ | |
{name: 'John', surname: 'Doe', age: 35}, | |
{name: 'John 2', surname: 'Doe 2', age: 19}, | |
{name: 'John 3', surname: 'Doe 3', age: 28}, | |
{name: 'John 4', surname: 'Doe 4', age: 16}, | |
{name: 'John 5', surname: 'Doe 5', age: 39} | |
]; | |
//Iterate over users and sort them by age, pick first and transform to a sentence | |
var res = _.chain(users) | |
.filter(function (user) { | |
return user.age > 20; | |
}) | |
.sortBy(function (user) { | |
return -user.age; | |
}) | |
.map(function (user) { | |
return 'My name is ' + user.name + ' ' + user.surname + ', and I\'m ' + user.age + ' old'; | |
}) | |
.first() | |
.value(); | |
console.log(res); //My name is John 5 Doe 5, and I'm 39 old | |
//We could also reuse the functions and get something as: | |
// var res = _.chain(users) | |
// .filter(ageOver.bind(null, 20)) | |
// .sortBy(sortByAge) //or use also _.negate(sortByAge) to get different effect | |
// .map(formatUserTitle) | |
// .first() | |
// .value(); | |
//Same thing with ES6 | |
// var res = _.chain(users) | |
// .filter(user => user.age > 20) | |
// .sortBy(user => -user.age) | |
// .map(user => `My name is ${user.name} ${user.surname} and I'm ${user.age} old`) | |
// .first() | |
// .value(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment