我有这段 javascript 代码:
function arrayMapper(mappingFunc) {
return items => items.map(mappingFunc);
}
function fooTransformer(tem) {
return (...); // do something with item and returns a value
}
function barTransformer(tem) {
return (...); // do something with item and returns a value
}
const foosTransformer = arrayMapper(fooTransformer);
const barsTransformer = arrayMapper(barTransformer);
(...)
foosTransformer([1, 2, 3]);
我想知道像我的 arrayMapper
函数这样的东西是否会原生存在于像 lodash 这样的东西中,只是为了避免重新发明轮子。
最佳答案
你实际上在做的是 currying map 功能(从右边开始)。
Lodash 允许您这样做:
const mapper = _.curryRight(_.map);
const square = mapper(x => x ** 2);
console.log(
square([1, 2, 3]) // [1, 4, 9]
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
话虽这么说,为这么小的功能引入整个库肯定是矫枉过正。也许如果你正在使用 npm,你可以只使用 npm install lodash.curryright lodash.map
并只使用那些,但这仍然可能是不必要的。
关于javascript - lodash中的一个数组映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44029877/