Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In lodash.js, will it cache the result for `.value()` method?

For example, I have codes (coffeescript) like this:

sortedLatLng = _(w)
    .sortBy (x) -> x.time
    .map (x) -> [x.longitude,x.latitude]
    .uniq((x)-> x[0].toFixed(3) + "," + x[1].toFixed(3))   # keep three decimal to merge nearby points
console.log(sortedLatLng.value())
myFunction1(sortedLatLng.value())
myFunction2(sortedLatLng.value())
console.log(sortedLatLng.reverse().value())

This may be chained by other lodash method later. Meanwhile, its value may be necessary to be extracted. I was justing wonder whether it will cache the result. I didn't find how it is implemented in its documentation..

Will it be calculated once or twice for:

myFunction1(sortedLatLng.value())
myFunction2(sortedLatLng.value())

Does anyone have ideas about this?

like image 328
Hanfei Sun Avatar asked May 22 '15 03:05

Hanfei Sun


People also ask

Is Lodash heavy?

While lodash offeres a tremendous library of functionality, much of it is no longer required, and the cost of importing lodash into your application can be huge, well over 600kb if your compiler doesn't shake the unrequired code, or you use lodash throughout your application.

How does Lodash get work?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.


1 Answers

When you create a lodash wrapper, the wrapped value is stored within the wrapper. For example:

var wrapper = _([ 1, 2, 3 ]);

Here, [ 1, 2, 3 ] is stored in wrapper, and any chained operations added to the wrapper are passed this value. Chained operations are stored, not executed. For example:

var wrapper = _([ 1, 2, 3 ]).map(function(item) {
    console.log('mapping');
    return item;
});

This code creates a wrapper with a map() operation, but doesn't execute it. Instead, it stores the chained operations so that when value() is called, it can execute them:

var wrapper = _([ 1, 2, 3 ]).map(function(item) {
    console.log('mapping');
    return item;
});

wrapper.value()
// mapping
// ...

Calling value() again on this wrapper will simply repeat the same operations on the wrapped value - results aren't cached.

like image 137
Adam Boduch Avatar answered Oct 16 '22 23:10

Adam Boduch