简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM