JavaScript实现惰性求值链式调用时函数顺序传参执行问题求助
问题根因
- 执行顺序错误:原
evaluate方法先遍历所有注册函数,再遍历数组元素,导致每个函数都独立处理原始数组,最终结果长度是「数组长度 × 函数数量」,和预期不符 - 无链式传递:每个函数的执行结果没有作为下一个函数的入参,所有函数都只处理原始输入值
- 结果污染:
resultedArray没有在每次调用evaluate时清空,多次调用会出现结果累加的问题 - 冗余逻辑:
add方法中存在无用的参数过滤逻辑,参数校验规则也不符合业务需求
修复后完整代码
class Lazy { constructor() { this.functions = []; this.counter = 0; this.resultedArray = []; } add(func, ...args) { // 校验函数参数数量:第一个参数为上一步返回值,额外参数为用户传入的args const requiredParamCount = args.length + 1; if (func.length !== requiredParamCount) { console.log(`Missing parameters for ${func.name} function: need ${requiredParamCount} params, but function only accepts ${func.length}`); return this; } this.counter++; this.functions.push({ func: func, args: args.length > 0 ? args : undefined }); return this; } evaluate(array) { // 每次调用先清空历史结果,避免污染 this.resultedArray = []; if (this.counter === 0) { console.log(array); return array; } // 遍历每个输入元素,按顺序执行所有注册函数 array.forEach(item => { let currentValue = item; this.functions.forEach(({func, args}) => { currentValue = args ? func(currentValue, ...args) : func(currentValue); }); this.resultedArray.push(currentValue); }); console.log(this.resultedArray); return this.resultedArray; } } // 测试用例 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]); // 输出:[3,5,7] 符合预期
核心修改说明
- 调整遍历顺序:改为先遍历数组元素,再让单个元素依次通过所有注册函数处理,保证输出结果长度和输入数组一致
- 增加链式传递:每个函数的执行结果保存在
currentValue变量中,作为下一个函数的第一个入参 - 结果初始化:每次调用
evaluate时先清空结果数组,避免多次调用的结果互相污染 - 优化参数校验:统一参数校验逻辑,确保传入的函数参数数量和用户传入的额外参数数量匹配
内容的提问来源于stack exchange,提问作者pleka7
相关产品推荐
相关产品推荐

