gpt4 book ai didi

javascript - 使用 findIndex() 从非零元素开始

转载 作者:行者123 更新时间:2023-11-28 16:53:14 27 4
gpt4 key购买 nike

我想在从零以外的元素开始的数组上使用 findIndex() 。我编写了以下代码,该代码对我有用,但是有更干净的解决方案吗?

let desiredLastElementIndex = refundRequests.map((e,i) =>{
if(i<numberOfTickets){
return 0
}else{
return Math.round(e.purchasersMinimumPrice - refundRequests[i-1].purchasersMinimumPrice)
}
}).findIndex((e, i) => findIndex((e, i) => e !== 0)

例如,当使用indexOf时,我可以传递我想要开始的索引作为第二个参数。

理想情况下,我想做一些类似的事情......

    let desiredLastElementIndex = refundRequests.findIndex((e, i) => {
e.purchasersMinimumPrice !== refundRequests[i+1].purchasersMinimumPrice
}, INDEXTOSTARTFROM) + 1

最佳答案

您可以定义一个名为 fromIndex() 的辅助方法来包装回调函数,然后再将其传递给 Array.prototype.find()Array.prototype.findIndex() 。它可以包装回调的其他函数是 Array.prototype.filter() , Array.prototype.forEach() ,和Array.prototype.some() .

function fromIndex(cb, index) {
return function (e, i, a) {
return i >= index && cb.call(this, e, i, a);
};
}

const array = [3, 7, 5, 1, 9];
const f = element => element > 4;

console.log(`value ${array.find(f)} index ${array.findIndex(f)}`);
console.log(`value ${array.find(fromIndex(f, 3))} index ${array.findIndex(fromIndex(f, 3))}`);

在您的示例中,用法如下所示:

let desiredLastElementIndex = refundRequests.findIndex(fromIndex((e, i) => {
e.purchasersMinimumPrice !== refundRequests[i + 1].purchasersMinimumPrice
}, INDEXTOSTARTFROM)) + 1
<小时/>

为了获得一些额外的乐趣,您可以专门为 find()findIndex() 定义一些 iteratee-last 柯里化(Currying)函数:

const fromIndex = (cb, index = 0) => (e, i, a) => (
i >= index && cb(e, i, a)
);
const wrap = (impl, apply) => (...args) => (
f => iteratee => impl(iteratee, f)
)(
apply(...args)
);

const find = wrap((array, fn) => array.find(fn), fromIndex);
const findIndex = wrap((array, fn) => array.findIndex(fn), fromIndex);

const array = [3, 7, 5, 1, 9];
const f = element => element > 4;

console.log(`value ${find(f)(array)} index ${findIndex(f)(array)}`);
console.log(`value ${find(f, 3)(array)} index ${findIndex(f, 3)(array)}`);

如果/当 F# style pipeline operator一旦符合规范,这将使这些部分功能看起来非常有吸引力:

// find() and findIndex() defined as above
const array = [3, 7, 5, 1, 9];
const f = element => element > 4;

// value 7 index 1
console.log(`value ${array |> find(f)} index ${array |> findIndex(f)}`);
// value 9 index 4
console.log(`value ${array |> find(f, 3)} index ${array |> findIndex(f, 3)}`);

关于javascript - 使用 findIndex() 从非零元素开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59687485/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com