10 个可用 ES6 替代的 Lodash 特性

Dan Prince

Lodash 现在是 npm 上被依赖最多的包，但如果你在使用 ES6 的话，实际上你可能不再需要它了。在本文中，我们将使用原生的集合方法与箭头函数还有一些其它新的特性来帮我们更简便地实现许多热门的用例。

1. Map, Filter, Reduce

``````_.map([1, 2, 3], function(n) { return n * 3; });
// [3, 6, 9]
_.reduce([1, 2, 3], function(total, n) { return total + n; }, 0);
// 6
_.filter([1, 2, 3], function(n) { return n <= 2; });
// [1, 2]

// 变为

[1, 2, 3].map(n => n * 3);
[1, 2, 3].reduce((total, n) => total + n);
[1, 2, 3].filter(n => n <= 2);
``````

``````_.head([1, 2, 3]);
// 1
_.tail([1, 2, 3]);
// [2, 3]

// 变为

const [head, ...tail] = [1, 2, 3];
``````

``````_.initial([1, 2, 3]);
// -> [1, 2]
_.last([1, 2, 3]);
// 3

// 变为

const [last, ...initial] = [1, 2, 3].reverse();
``````

``````const xs = [1, 2, 3];
const [last, ...initial] = [...xs].reverse();
``````

``````var say = _.rest(function(what, names) {
var last = _.last(names);
var initial = _.initial(names);
var finalSeparator = (_.size(names) > 1 ? ', & ' : '');
return what + ' ' + initial.join(', ') +
finalSeparator + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"

// 变为

const say = (what, ...names) => {
const [last, ...initial] = names.reverse();
const finalSeparator = (names.length > 1 ? ', &' : '');
return `\${what} \${initial.join(', ')} \${finalSeparator} \${last}`;
};

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"
``````

4. Curry

``````function add(a, b) {
return a + b;
}
// 3

// 变为

const add = a => b => a + b;
// 3
``````

``````var lodashAdd = _.curry(function(a, b) {
return a + b;
});
// 0
//function wrapper() {
//  var length = arguments.length,
//  args = Array(length),
//  index = length;
//
//  while (index--) {
//    args[index] = arguments[index];
//  }…

// 变为

const es6Add = a => b => a + b;
// 1
// function b => a + b
``````

``````_.map(_.prop('name'))(people);

// 变为

people.map(person => person.name);
``````

5. Partial

``````var greet = function(greeting, name) {
return greeting + ' ' + name;
};

var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// "hello fred"

// 变为

const sayHelloTo = name => greet('hello', name);
sayHelloTo('fred');
// "hello fred"
``````

``````const sayHelloTo = (name, ...args) => greet('hello', name, ...args);
sayHelloTo('fred', 1, 2, 3);
// "hello fred"
``````

6. Operators

Lodash 把很多句法操作符重新实现成了函数，所以它们可以被传入集合方法。

``````_.eq(3, 3);
// true
// 11
_.map([1, 2, 3], function(n) {
return _.multiply(n, 10);
});
// [10, 20, 30]
// 6

// 变为

3 === 3
10 + 1
[1, 2, 3].map(n => n * 10);
[1, 2, 3].reduce((total, n) => total + n);
``````

7. Paths

``````var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };

_.at(object, ['a[0].b.c', 'a[1]']);
// [3, 4]
_.at(['a', 'b', 'c'], 0, 2);
// ['a', 'c']

// 变为

[
obj => obj.a[0].b.c,
obj => obj.a[1]
].map(path => path(object));

[
arr => arr[0],
arr => arr[2]
].map(path => path(['a', 'b', 'c']));
``````

``````const getFirstPerson = people => people[0];
const getPostCode = person => person.address.postcode;
const getFirstPostCode = people => getPostCode(getFirstPerson(people));
``````

``````const getFirstNPeople = n => people => people.slice(0, n);

const getFirst5People = getFirstNPeople(5);
const getFirst5PostCodes = people => getFirst5People(people).map(getPostCode);
``````

8. Pick

pick 工具能让我们从一个对象中选择我们想要的属性。我们也能通过解构与对象字面量简写来获取同样的结果。

``````var object = { 'a': 1, 'b': '2', 'c': 3 };

return _.pick(object, ['a', 'c']);
// { a: 1, c: 3 }

// 变为

const { a, c } = { a: 1, b: 2, c: 3 };

return { a, c };
``````

9. Constant, Identity, Noop

Lodash 提供了一些工具函数来创建简单的具某一特定行为的函数。

``````_.constant({ 'a': 1 })();
// { a: 1 }
_.identity({ user: 'fred' });
// { user: 'fred' }
_.noop();
// undefined
``````

``````const constant = x => () => x;
const identity = x => x;
const noop = () => undefined;
``````

``````(() => ({ a: 1 }))();
// { a: 1 }
(x => x)({ user: 'fred' });
// { user: 'fred' }
(() => undefined)();
// undefined
``````

10. Chaining & Flow

Lodash 提供了一些函数来帮我们编写链式的语句。在大多情况下，内置的集合函数会返回一个数组实例，能直接被链式调用。但某些情况下，这些方法会改变这个集合，这样就不可能再直接地链式调用了（译者注：需要自己返回实例）。

``````_([1, 2, 3])
.tap(function(array) {
// 修改输入函数
array.pop();
})
.reverse()
.value();
// [2, 1]

// 变为

const pipeline = [
array => { array.pop(); return array; },
array => array.reverse()
];

pipeline.reduce((xs, f) => f(xs), [1, 2, 3]);
``````

``````const pipe = functions => data => {
return functions.reduce(
(value, func) => func(value),
data
);
};

const pipeline = pipe([
x => x * 2,
x => x / 3,
x => x > 5,
b => !b
]);

pipeline(5);
// true
pipeline(20);
// false
``````

总结

Lodash 仍然还是一个非常优秀的库，这篇文章只提供了一个新鲜的观点，JavaScript 的进化版是如何让我们在一些我们之前可能不得不依赖一些工具模块的场景里允许我们直接解决问题的。