目前, Lodash是最受依赖的npm软件包 ,但是如果您使用的是ES6,则可能实际上并不需要它。
在本文中,我们将研究使用带有箭头功能和其他新ES6功能的本机收集方法,以帮助我们绕开许多流行的用例。
1.映射,过滤,缩小
这些收集方法使转换数据变得轻而易举,并获得了几乎所有人的支持。 我们可以将它们与箭头函数配对,以帮助我们为Lodash提供的实现编写简洁的替代方案:
_.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]
// becomes
[1, 2, 3].map(n => n * 3);
[1, 2, 3].reduce((total, n) => total + n);
[1, 2, 3].filter(n => n <= 2);
它也不止于此。 如果我们使用的是现代浏览器,我们还可以使用find , some , every和reduceRight 。
2.头尾
分解语法使我们无需使用实用程序函数即可获得列表的开头和结尾:
_.head([1, 2, 3]);
// 1
_.tail([1, 2, 3]);
// [2, 3]
// becomes
const [head, ...tail] = [1, 2, 3];
也可以通过类似的方式获取初始元素和最后一个元素:
_.initial([1, 2, 3]);
// -> [1, 2]
_.last([1, 2, 3]);
// 3
// becomes
const [last, ...initial] = [1, 2, 3].reverse();
如果您发现反向更改数据结构很烦人,则可以在调用反向之前使用spread运算符克隆数组:
const xs = [1, 2, 3];
const [last, ...initial] = [...xs].reverse();
3.休息和传播
其余函数和传播函数使我们能够定义和调用接受可变数量参数的函数。 ES6为这两种操作引入了专用语法:
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"
// becomes
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.咖喱
如果没有更高层次的语言,如[打字稿] [5]或[流量] [6],我们不能给我们的函数类型签名,这使得讨好相当困难的。 当我们收到咖喱函数时,很难知道已经提供了多少个参数,接下来需要提供哪些参数。 使用箭头函数,我们可以显式定义咖喱函数,使其他程序员更容易理解它们:
function add(a, b) {
return a + b;
}
var curriedAdd = _.curry(add);
var add2 = curriedAdd(2);
add2(1);
// 3
// becomes
const add = a => b => a + b;
const add2 = add(2);
add2(1);
// 3
这些明确管理的箭头功能对于调试特别重要:
var lodashAdd = _.curry(function(a, b) {
return a + b;
});
var add3 = lodashAdd(3);
console.log(add3.length)
// 0
console.log(add3);
// function (a, b) {
// /* [wrapped with _.curry & _.partial] */
// return a + b;
// }
// becomes
const es6Add = a => b => a + b;
const add3 = es6Add(3);
console.log(add3.length);
// 1
console.log(add3);
// function b => a + b
如果我们使用lodash / fp或ramda之类的功能库,我们还可以使用箭头来消除对自动咖喱风格的需要:
_.map(_.prop('name'))(people);
// becomes
people.map(person => person.name);
5.部分
与currying一样,我们可以使用箭头函数使部分应用程序变得简单明了:
var greet = function(greeting, name) {
return greeting + ' ' + name;
};
var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// "hello fred"
// becomes
const sayHelloTo = name => greet('hello', name);
sayHelloTo('fred');
// "hello fred"
还可以将rest参数与spread运算符一起使用来部分应用可变参数函数:
const sayHelloTo = (name, ...args) => greet('hello', name, ...args);
sayHelloTo('fred', 1, 2, 3);
// "hello fred"
6.运营商
Lodash附带了许多函数,这些函数将语法运算符重新实现为函数,以便可以将其传递给收集方法。
在大多数情况下,箭头函数使它们简单而简短,因此我们可以内联定义它们:
_.eq(3, 3);
// true
_.add(10, 1);
// 11
_.map([1, 2, 3], function(n) {
return _.multiply(n, 10);
});
// [10, 20, 30]
_.reduce([1, 2, 3], _.add);
// 6
// becomes
3 === 3
10 + 1
[1, 2, 3].map(n => n * 10);
[1, 2, 3].reduce((total, n) => total + n);
7.路径
Lodash的许多函数都将路径作为字符串或数组。 我们可以使用箭头函数来创建更多可重用的路径:
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']
// becomes
[
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实用程序使我们可以从目标对象中选择所需的属性。 我们可以使用解构和速记对象文字来达到相同的结果:
var object = { 'a': 1, 'b': '2', 'c': 3 };
return _.pick(object, ['a', 'c']);
// { a: 1, c: 3 }
// becomes
const { a, c } = { a: 1, b: 2, c: 3 };
return { a, c };
9.常数,身份,否
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.链接与流程
Lodash提供了一些功能来帮助我们编写链式语句。 在许多情况下,内置的collection方法返回可以直接链接的数组实例,但是在某些情况下该方法使collection发生变化时,这是不可能的。
但是,我们可以定义与箭头函数数组相同的转换:
_([1, 2, 3])
.tap(function(array) {
// Mutate input array.
array.pop();
})
.reverse()
.value();
// [2, 1]
// becomes
const pipeline = [
array => { array.pop(); return array; },
array => array.reverse()
];
pipeline.reduce((xs, f) => f(xs), [1, 2, 3]);
这样,我们甚至不必考虑tap和thru之间的区别。 将这种减少归结为实用工具功能,是了不起的通用工具:
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的演进版本如何使我们能够解决以前依赖实用程序模块的情况下的一些问题。
不要忽略它。 相反,下次您要进行抽象时,请考虑是否可以使用简单函数代替!
马克·布朗 ( Mark Brown )对这篇文章进行了同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态!
From: https://www.sitepoint.com/lodash-features-replace-es6/