Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js: how to chain custom functions

Tags:

Using Underscore.js, I can write the following which returns 42:

_([42, 43]).chain()     .first()     .value() 

I have custom function, not part of Underscore.js called double():

function double(value) { return value * 2; }; 

I would like to be able to call this function in an Underscore chain, as if it was part of Underscore. I would like to write the following, which I'd like to return 84:

_([42, 43]).chain()     .first()     .double()     .value() 

This can't work since Underscore doesn't define double(). I could use tap() as in:

_([42, 43]).chain()     .first()     .tap(double)     .value() 

This is valid, but tap applies the function to its argument and returns the argument, not the result of the function. So it looks to me like I would need a sort of tap that returns the result of the function applied to its argument. Is there anything like this in Underscore.js? Am I missing something terribly obvious?

like image 452
avernet Avatar asked Oct 15 '10 19:10

avernet


People also ask

Can JavaScript function include underscore?

Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private.

What is the use of _ in JavaScript?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

Is Lodash still needed 2022?

But Sometimes You Do Need Lodash Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.

How do I run an underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


1 Answers

Not finding a tap that returns the value returns by the function is runs, I define one which I can take and add to _:

_.mixin({take: function(obj, interceptor) {     return interceptor(obj); }}); 

Then assuming I have:

function double(value) { return value * 2; }; 

I can write:

_([42, 43]).chain()     .first()             // 42     .take(double)        // Applies double to 42     .value()             // 84 

You can look at take as map on objects, instead of lists. Want to experiment with this? See this example on jsFiddle.

like image 154
avernet Avatar answered Oct 15 '22 23:10

avernet