我正在寻找一种函数式方法来查找数组中的第一个结果。
let result;
for (let i = 0; i < array.length; i++) {
result = functionThatCalulatesResult(array[i]);
if (result) {
break;
}
}是势在必行的。
const item = array.find(i => functionThatCalulatesResult(i));但现在我必须重新计算结果。
const result = array.reduce(
(result, item) => result ? result : functionThatCalulatesResult(i),
undefined
);但是reduce会遍历所有不需要迭代的项。
我在找像这样的东西
const result = firstResult(array, i => functionThatCalulatesResult(i));这将返回函数的第一个真实结果,而不会迭代超过第一个结果的项。
我能想到的最有效的方法是
const firstResult = (array, func) => {
let result;
array.some(i => result = func(i));
return result;
}但随着结果的变异,它并不是纯功能的。
编辑:
对于询问数组中是什么的人,我正在尝试找到在此函数中查找返回排序方向的参数的最有效方法。
https://stackblitz.com/edit/typescript-syhjq4
我使用的是reduce,但由于排序函数无论如何都会使数组发生突变,所以我切换到了带有突变的some。
发布于 2019-01-11 08:18:57
如果我正确理解了您的问题,也许您可以通过首先将值的array减少为Set来实现所需的功能。
这将意味着如下所示的后续find()仅对唯一值进行操作(这避免了重复数组项上的functionThatCalulatesResult()的冗余迭代和重新处理):
// Mock functionThatCalulatesResult() to illustrate this answers
// idea. The function returns truthy when value 5 encountered
function functionThatCalulatesResult(i) {
console.log('visiting:', i )
if(i === 5) {
return true;
}
}
var array = [1,2,3,1,3,1,5,6];
// Reducing array to unique set of values avoid reprocessing of
// functionThatCalulatesResult() on duplicate values that don't
// return truthy
var result = Array.from(new Set(array)).find(functionThatCalulatesResult);
console.log('result', result)
https://stackoverflow.com/questions/54138716
复制相似问题