Compositional advantage of Lodash/Underscore syntax over vanilla JS syntax

I'm familiarizing myself with some of the Lodash/Underscore methods and have a fundamental question about syntax.


If I have a list of user objects and want to filter the list by those users whose ages are less than 40, I can write the following vanilla JavaScript:

// Vanilla JS
var result = users.filter((d) => d.age < 40);

LoDash/Underscore offers an alternative syntax to produce the same result:

// Lodash, Underscore
var result = _.filter(users, (d) => d.age < 40); 

Both of these produce the same result and return an array.

What are the compositional advantages, if any, to using the latter syntax? Why is it preferable to using the plain JS syntax?


Edit

Because I'm receiving answers like "one requires an additional library and one doesn't" and "they execute different code", I want to clarify.

From a function composition standpoint, are there any advantages to using the lodash/underscore method over the Vanilla JS method?


Imagine you have the following function compose .

function compose(f, g) {
  return function apply(...args) {
    return g(f(...args));
  }
}

You can use it to compose two functions together to create a single function.

const inc = x => x + 1;
const double = x => x * 2;

const doubleAndInc = compose(double, inc);
doubleAndInc(3) // 7
const incAndDouble = compose(inc, double);
doubleAndInc(3) // 8

These functions can be composed because they only rely on their arguments . The same is true for Lodash's filter function.

const filterFirst = compose(_.filter, _.head);
filterFirst([1, 2, 3], x => x % 2 == 0); // 2

Array.prototype.filter isn't called with an array as an argument. Instead, it uses its internal this value—which will usually be the array the method was called on.

The compose function doesn't know anything about this . It only works with are arguments and return values, which means it can't be used to compose functions that rely on this instead of just arguments.

链接地址: http://www.djcxy.com/p/27674.html

上一篇: 有没有在nodejs代码中从package.json获取版本的方法?

下一篇: 与vanilla JS语法相比,Lodash / Underscore语法的组合优势