gpt4 book ai didi

javascript - 如何在无限循环中重用数组函数

转载 作者:行者123 更新时间:2023-11-30 11:36:52 25 4
gpt4 key购买 nike

真正的代码比较大,就不贴了。它看起来很像这样:

class A {
process(source) {
// I perform several operations with array helper functions here:
const filtered = source.filter(item => item);
const condition = filtered.some(item => item);

if (condition) {
const mapped = source.map(item => /* Mapping operations... */);
const sorted = mapped.sort((a, b) => { /* Some sort conditions... */ });
return sorted;
} else {
const mapped2 = filtered.map(item => /* A different mapping operation... */);
return mapped2;
}
}
}

const a = new A();

while (true) {
const source = getSourceFromSomewhere(); // Array (40 - 50 items aprox)
const b = a.process(source);
// ...
}

The problem: Basically, performance; "Don't make functions within a loop".

在每次迭代中都会创建一堆匿名函数。

我的解决方案:

class A {
// Predefine it:
sort() { /* Sort logic */ }
map() { /* Map logic */ }
map2() { /* Map logic */ }
filter() { /* Filter logic */ }
some() { /* Condition */ }

process(source) {
const filtered = source.filter(this.filter); // Note: Scope of 'this' is changed.
const condition = filtered.some(this.some);

if (condition) {
const mapped = source.map(this.map);
const sorted = mapped.sort(this.sort);
return sorted;
} else {
const mapped2 = filtered.map(this.map2);
return mapped2;
}
}
}

Another problem: Some of this functions need access to properties of the object itself, but the scope of this has been changed.

值得调用 .bind(this) 而不是创建匿名函数吗?还是几乎一样?

如果是我,你会怎么做?

提前致谢。

最佳答案

要在类中初始化绑定(bind)函数,您可以这样做

class Test {
fn = (t) => this[t]
}

基本上与您想做的一样。

关于javascript - 如何在无限循环中重用数组函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44091748/

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