Chaining in lodash with custom features

Is there a way to get my own custom function in the lodash chain. For example, for example:

var l = [1,2,3] var add = function(a, b){return a+b} var r =_.chain(l).find(function(a){return a>1}).add(5).value() =>r = 7 
+8
javascript lodash
source share
3 answers

What you are looking for is a way to extend the lodash prototype. It works so well that you can do it easily with the mixin utility function. Check the docs here: http://lodash.com/docs#mixin

In your example, it will look like this:

 var l = [1,2,3]; var add = function(a, b){return a+b} _.mixin({ add: add }); var r =_.chain(l).find(function(a){return a>1}).add(5).value() console.log(r); ==> 7 

and here is a live sample on the fiddle: http://jsfiddle.net/g2A9C/

+15
source share

After @stride anwswer, I came up with a more general solution using _.mixin :

 function add(a, b, c) { return a + b + c } function sub(a, b, c) { return a - b - c } _.mixin({ run: function (v, f) { var args = Array.prototype.slice.call(arguments, 2) args.unshift(v) return f.apply(this, args) } }) var r = _.chain(1).run(add, 1, 1).run(sub, 2, 2).value() console.log(r) -> -1 1 + 1 + 1 - 2 - 2 = -1 

http://jsbin.com/iyEhaMa/1/

In the end, I wonder why this is not a built-in function in lodash.

+5
source share

Another option is to simply compose the structure of the chain and leverage functions with _.flow .

From DOCS:

[Flow] Creates a function that returns the result of calling this function with this binding of the created function, where each successive call receives the return value of the previous one.

This means that each function within the stream will receive the input of the previous one. In practice, this means that we are not limited to using only the Lodash API methods, but we can mix and match any function that we represent, until the next one can process this return value.

 var l = [1,2,3] var add = _.curry((a, b) => a + b); _.flow( _.find(a => a > 1), add(5), )(l); // => 7 

NB. This example uses the functional version of Lodash, if you do not want or cannot use the one that you can still achieve the same result, check out my other answer to another question about Lodash .

+3
source share

All Articles