Sum Odd Numbers

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
Base
function sumOddNumbers(nums: number[]) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    // Modulo operator against 2 will always return either 0 or 1
    // If odd, accumulate, otherwise return running total
    // Make sure we filter out floats
    if (Number.isInteger(nums[i]) && nums[i] % 2 !== 0) sum += nums[i];
  }
  return sum;
}

sumOddNumbers([-1, -2, -3, 4, 5]);
ready
Reduce
function sumOddNumbersSlower(nums: number[]) {
  return nums.reduce((sum, num) => Number.isInteger(num) && num % 2 !== 0 ? sum + num : sum, 0);
}

sumOddNumbersSlower([-1, -2, -3, 4, 5]);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.