所以基本上我需要實作一個懶惰的評估。.add() 將函式作為引數和任何其他任意引數。作為引數傳遞的函式稍后運行(呼叫評估時),其他引數(如果有)作為該函式的引數。
基本上我的問題是當我運行以陣列作為引數的 .evaluate() 時,作為引數傳遞給 add() 的函式不會一次呼叫一個并回傳結果并將其作為下一個的引數。
class Lazy {
constructor() {
this.functions = [];
this.counter = 0;
this.resultedArray = [];
}
add(func, ...args) {
if (args.length > 0) {
this.counter ;
const argsArrayNumeric = args.filter((item) => typeof item === "number");
this.functions.push({
func: func,
args: args,
});
} else {
if (func.length <= args.length 1 || func.length === args.length) {
this.counter ;
this.functions.push({ func: func });
} else {
console.log("Missing parameters for " func.name " function");
}
}
return this;
}
evaluate(array) {
if (this.counter > 0) {
let result;
this.functions.map((obj, index) => {
array.map((item, index) => {
console.log(obj);
if (obj.func && obj.args) {
result = obj.func(item, ...obj.args);
} else {
result = obj.func(item);
}
this.resultedArray.push(result);
});
});
console.log(this.resultedArray);
} else {
console.log(array);
}
}
}
const s = new Lazy();
const timesTwo = (a) => {
return a * 2;
};
const plus = (a, b) => {
return a b;
};
s.add(timesTwo).add(plus, 1).evaluate([1, 2, 3]);
//correct result is [3,5,7] but i have [ 2, 4, 6, 2, 3, 4 ]
uj5u.com熱心網友回復:
有幾個問題evaluate:
push當您有多個功能時,將被執行太多次。map不真正映射時不要使用。.map()回傳一個結果。- 從預期的輸出來看,您似乎需要從右到左應用函式,而不是從左到右
this.counter并沒有真正發揮作用。this.functions陣列的長度應該是你所需要的。- 結果不應該列印在方法中,而是回傳。列印它或用它做其他事情是呼叫者的責任。
所有這些都可以reduceRight像這樣使用:
evaluate(array) {
return this.functions.reduceRight((result, obj) =>
result.map((item) => obj.func(item, ...(obj.args || [])))
, array);
}
在主程式中,列印回傳值:
console.log(s.add(plus, 1).add(timesTwo).evaluate([1, 2, 3]));
該add方法也有一些奇怪的邏輯,例如:
- 當第一個
if條件為假時,else塊以 開始args.length == 0。然后很奇怪看到條件args.length...它真的是0! - 如果第一個條件
func.length <= args.length 1 || func.length === args.length為假,那么第二個條件肯定也永遠為假。它不應該在那里。 argsArrayNumeric從不使用。
總而言之,代碼似乎可以簡化為以下代碼段:
class Lazy {
constructor() {
this.functions = [];
}
add(func, ...args) {
this.functions.push({ func, args });
if (func.length > args.length 1) {
throw ValueError(`Missing parameters for ${func.name} function`);
}
return this;
}
evaluate(array) {
return this.functions.reduceRight((result, obj) =>
result.map((item) => obj.func(item, ...(obj.args || [])))
, array);
}
}
const timesTwo = (a) => a * 2;
const plus = (a, b) => a b;
const s = new Lazy();
console.log(s.add(plus, 1).add(timesTwo).evaluate([1, 2, 3])); // [3, 5, 7]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/370628.html
標籤:javascript 算法
上一篇:動態加載帶有位置的多邊形
下一篇:為什么當我們用let定義for回圈變數時,不使用IFFE技術,我們可以將它的特定值設定為函式而不會丟失它?[復制]
