In underscore/lodash, how to avoid duplicate calculation in a `map` method?

144 Views Asked by At

Here is my code:

var transformed = _(original).map(function (c) {
    return {
        lat: wgs2gcj(c.latitude, c.longitude).lat
        lng: wgs2gcj(c.latitude, c.longitude).lng
    }
});

Let's say wgs2gcj is a function from a third-party library and will take a long time to compute. Is there a way to do the calculation only once?

2

There are 2 best solutions below

1
On BEST ANSWER
transformed = _(original).map(function (c) {
    var coordinates = wgs2gcj(c.latitude, c.longitude);

    return {
        lat: coordinates.lat
        lng: coordinates.lng
    }
});
0
On

For less code, you could use pick() as well:

_(original)
    .map(function(c) {
        return _.pick(wgs2gcj(c.latitude, c.longitude), 'lat', 'lng');
    })
    .value();