You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现符合链式调用与类型判断要求的sum函数?基于Object.prototype.valueOf

实现满足特定要求的sum函数问题

题目要求

需要实现一个sum函数,满足以下输出要求:

const sum1 = sum(1)
sum1(2)() // return 3
sum1(3)() // return 4

// 不赋值给变量直接调用
sum(1)(2)(3)() // return 6
sum(5)(-1)(2)() // return 6

sum(1)(2)(4) == 7 // true
sum(1)(2)(4) === 7 // false

sum函数的定义模板如下:

/**
 * @param {number} num
 */
function sum(num) {
  // your code here
}

题目提示需要深入理解Object.prototype.valueOf()。


我的尝试与遇到的问题

我编写了测试代码来验证预期返回值,也明白当需要将返回值转换为原始类型(尤其是数值类型)时,Object.prototype.valueOf会生效。但在实现过程中遇到了不少问题:

  • 为了满足sum(1)(2)(4) == 7 -> true这个测试用例,我尝试使用useSum.prototype.valueOf,但发现必须通过new关键字才能让它生效,可这样返回的是object而非function,不符合调用要求。
  • 于是我添加了条件判断:有参数时返回函数,无参数时返回纯数值。
  • 虽然通过了部分测试用例,但sum(1)(2)(4) == 7 -> true这个用例还是失败了。
  • 执行sum1(2)() === 3后,再执行sum1(3)() === 4也失败了,this.accumulator无法识别它来自初始值为1的sum1实例。
  • 解决上述问题时又出现新问题:this.accumulator的残留值会影响sum(1)(2)(3)() === 6、sum(5)(-1)(2)() === 6这些测试用例的初始值计算。

我的测试代码如下:

/**
 * @param {number} num 
 */
function sum(num = 0) {
    if (this.accumulator) {
        this.accumulator += num;
    } else {
        this.accumulator = num;
        this.init = num;
    }
    const that = this
    function useSum(isEnd) {
        if (!isEnd) {
            return (addend) => sum(addend)
        }
        return that.accumulator
    }
    if (num) {
        useSum.prototype.valueOf = function() {
            return that.accumulator;
        }
        const result = new useSum(false);
        return result
    }
    const result = this.accumulator;
    this.accumulator = 0;
    return result
}


// test function
function expect(caseName, occasion) {
    function toBe(result) {
        console.log(`test case: ${caseName}`);
        if (occasion === result) {
            console.log("--> pass\n")
        } else {
            console.log(`--> fail, expect ${result}, got ${occasion}\n`)
        }
        return null
    }
    return { toBe }
}

// test cases from my pespective
const sum1 = sum(1);
expect("sum1(2)() === 3", sum1(2)()).toBe(3)
expect("sum1(3)() === 4", sum1(3)()).toBe(4)
expect("sum(1)(2)(3)() === 6", sum(1)(2)(3)()).toBe(6)
expect("sum(5)(-1)(2)() === 6", sum(5)(-1)(2)()).toBe(6)
expect("sum(1)(2)(4) == 7 -> true", sum(1)(2)(4) == 7).toBe(true)
expect("sum(1)(2)(4) === 7 -> false", sum(1)(2)(4) === 7).toBe(false)

恳请各位提供相关解决思路。


内容的提问来源于stack exchange,提问作者YPChen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:10:29