gpt4 book ai didi

JavaScript 映射并同时查找 : findMap?

转载 作者:行者123 更新时间:2023-12-01 15:29:35 24 4
gpt4 key购买 nike

如果不使用 for 循环,你将如何重写它?

const a = [2, 5, 78, 4];
const expensiveFunction = n => 2 * n;

let result;

// Find the first number
for (let i = 0; i < a.length; i++) {
const r = expensiveFunction(a[i]);

if (r > 100) {
result = r;
break;
}
}

console.log(result);

我天真的方法:
const result = a.map(expensiveFunction).find(x => x > 100);
console.log(result);

但这运行 expensiveFunction我想避免的所有元素。在上述情况下,我们应该避免运行 expensiveFunction(4) .

有些语言有 find_map (例如 Rust ),我没有在 lodash 和下划线中找到它。

最佳答案

内置map是贪婪的,所以你必须编写自己的懒惰版本:

const a = [2, 5, 78, 4];
const expensiveFunction = n => {
console.log('expensiveFunction for', n);
return 2 * n
};


function *map(a, fn) {
for(let x of a)
yield fn(x);
}

function find(a, fn) {
for(let x of a)
if (fn(x))
return x;
}



r = find(map(a, expensiveFunction), x => x > 100)
console.log('result', r)

不同于库存 map , 这个 map是一个生成器,根据需要返回(产生)结果,而不是一次处理整个数组。 findmap在这个例子中是“协程”并玩某种乒乓球游戏,其中 find要求结果和 map当被问到时交付它们。尽快 find对它所拥有的感到满意,它退出了, map ,因为没有人再要求它的结果了。
您也可以添加 map , find和 friend 们到 IteratorPrototype使它们可用于所有迭代器并能够使用点表示法:

const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));

Object.defineProperties(IteratorPrototype, {
map: {
value: function* (fn) {
for (let x of this) {
yield fn(x);
}
},
enumerable: false
},

find: {
value: function (fn) {
for (let x of this) {
if (fn(x))
return x;
}
},
enumerable: false
},

});

//

const a = [2, 5, 78, 4];
const expensiveFunction = n => {
console.log('expensiveFunction', n);
return 2 * n
};


let r = a.values().map(expensiveFunction).find(x => x > 100);

console.log(r)

这是一个基于这种技术的小型库: https://github.com/gebrkn/armita

关于JavaScript 映射并同时查找 : findMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760111/

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