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

/**
 * Calculates the sum of numbers, handles various input types.
 *
 * @param {...(number|string|Array<number|string>)} args - Numbers, strings representing numbers, or arrays of these to sum.
 * @returns {number} The sum of all valid numeric inputs. Returns 0 if no valid numbers are provided.
 */
function sum(...args) {
  let total = 0;

  function processValue(value) {
    if (typeof value === 'number') {
      total += value;
    } else if (typeof value === 'string') {
      const num = Number(value);
      if (!isNaN(num)) {
        total += num;
      }
    } else if (Array.isArray(value)) {
      value.forEach(processValue);
    }
  }

  args.forEach(processValue);

  return total;
}



// Test cases demonstrating various input types and handling of invalid inputs:
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, '2', 3)); // Output: 6
console.log(sum('1', '2', '3')); // Output: 6
console.log(sum(1, 'a', 3)); // Output: 4 (ignores 'a')
console.log(sum([1, 2, 3])); // Output: 6
console.log(sum([1, '2', 3])); // Output: 6
console.log(sum([1, 'a', 3])); // Output: 4 (ignores 'a')
console.log(sum(1, [2, '3'], 4)); // Output: 10
console.log(sum(1, [2, 'a', 4], 5)); // Output: 12 (ignores 'a')
console.log(sum()); // Output: 0
console.log(sum(null, undefined, NaN)); // Output: 0
console.log(sum("1.5", 2.5));  // Output: 4
console.log(sum("1,2", 3)); // Output: 4 (treats "1,2" as 1)


This improved version addresses several key aspects:

  • Handles various input types: Accepts numbers, strings that can be converted to numbers, and arrays (including nested arrays) containing a mix of these types.
  • Robust error handling: Gracefully handles invalid inputs (like non-numeric strings, null, undefined, NaN) by ignoring them.
  • Recursive array processing: Correctly sums numbers within nested arrays.
  • Clear function documentation: Includes a JSDoc comment explaining the function's purpose, parameters, and return value.
  • Comprehensive test cases: Demonstrates the function's behavior with different inputs, including edge cases.
  • Handles floating-point numbers: Correctly sums numbers with decimal values.

This function is now much more versatile and reliable for summing various data combinations in a frontend environment. It's also well-documented and tested, making it easier to understand and use.

posted @   王铁柱6  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示