Skip to content

Instantly share code, notes, and snippets.

@mulderu
Last active December 11, 2019 20:31
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 mulderu/330b8cbffd5a298790c739c897063a87 to your computer and use it in GitHub Desktop.
Save mulderu/330b8cbffd5a298790c739c897063a87 to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/sasanut/4
// ref : https://medium.com/@parshwamehta13/basics-of-method-chaining-in-javascript-using-lodash-16f1168cf066
// <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
var users = [
{
"user": "barney",
"age": 36
},
{
"user": "fred",
"age": 40
},
{
"user": "pebbles",
"age": 1
}
]
Log = console.log
// youngest = "pebbles is 1"
var youngest = _.head(
_.map(
_.sortBy(users, 'age')
, o=>o.user + ' is ' + o.age)
);
Log(youngest)
var youngest2 = _.chain(users)
.sortBy('age')
.map(o=>o.user + ' is ' + o.age)
.head()
.value();
Log(youngest2)
var chainedTransformer = _.chain(users)
.sortBy('age')
.map(o=>`${o.user} is ${o.age}`);
Log('youngest =>' + chainedTransformer.head().value())
Log('oldest =>' + chainedTransformer.reverse().head().value())
p = _.chain([1,2,3])
.map(x => [x, x*2, x*3])
.flatten()
.sort()
.value()
Log('hi:' + p)
let data3 = ['ab', 'cb', 'ef'];
const vowels =
(array) => _.filter(array, str => /[aeiou]/i.test(str))
_.mixin({vowels: vowels})
p = _.chain(data3)
.vowels()
.value();
Log(p)
p = _.chain(data3)
.thru(vowels)
.value();
Log(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment