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

Odin Project JS sumAll测试卡在RUN阶段,寻求解决帮助

sumAll测试卡住问题排查及修复

问题描述

运行The Odin Project的Foundation JS 05_sumAll练习测试时,测试卡在RUN阶段。已尝试删除目录重新克隆GitHub仓库、重装Jest,问题仍未解决,其他练习测试均正常执行。

原函数代码

const sumAll = function(min, max) {
    if (!Number.isInteger(min) || !Number.isInteger(max)) return 'ERROR';
    if (min < 0 || max < 0) return 'ERROR';
    if (min > max) [min, max] = [max, min]
    let sum = 0;
    for (let i = 0; min <= max; i++) {
        sum += i;
    }
    return sum;
};                  
sumAll(1, 4);

// Do not edit below this line
module.exports = sumAll;

测试代码

const sumAll = require('./sumAll')

describe('sumAll', () => {
  test('sums numbers within the range', () => {
    expect(sumAll(1, 4)).toEqual(10);
  });
  test('works with large numbers', () => {
    expect(sumAll(1, 4000)).toEqual(8002000);
  });
  test('works with larger number first', () => {
    expect(sumAll(123, 1)).toEqual(7626);
  });
  test('returns ERROR with negative numbers', () => {
    expect(sumAll(-10, 4)).toEqual('ERROR');
  });
  test('returns ERROR with non-number parameters', () => {
    expect(sumAll(10, "90")).toEqual('ERROR');
  });
  test('returns ERROR with non-number parameters', () => {
    expect(sumAll(10, [90, 1])).toEqual('ERROR');
  });
});

问题原因

函数中的for循环存在无限循环:

for (let i = 0; min <= max; i++) {
    sum += i;
}

循环条件min <= max在循环内部从未被修改,只要初始满足该条件(或交换后满足),循环会一直执行下去,导致测试卡住。同时逻辑错误:应该累加min到max的数值,而非从0开始累加i。

修复后的函数代码

const sumAll = function(min, max) {
    if (!Number.isInteger(min) || !Number.isInteger(max)) return 'ERROR';
    if (min < 0 || max < 0) return 'ERROR';
    if (min > max) [min, max] = [max, min];
    let sum = 0;
    // 遍历min到max的所有数值并累加
    for (let i = min; i <= max; i++) {
        sum += i;
    }
    return sum;
};                  
sumAll(1, 4);

// Do not edit below this line
module.exports = sumAll;

可选优化(用等差数列公式)

如果追求更高效率,可替换循环为数学计算,避免遍历:

const sumAll = function(min, max) {
    if (!Number.isInteger(min) || !Number.isInteger(max)) return 'ERROR';
    if (min < 0 || max < 0) return 'ERROR';
    if (min > max) [min, max] = [max, min];
    // 等差数列求和公式:项数 * (首项 + 末项) / 2
    return (max - min + 1) * (min + max) / 2;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:33:39