Skip to content

Latest commit

 

History

History
73 lines (55 loc) · 1.74 KB

File metadata and controls

73 lines (55 loc) · 1.74 KB

Separate odd and even numbers

The problem

You have a list of integers:

const integers = [1, 42, 7, 37, 2, ...]

Your goal is to separate odd and even numbers:

const separated = {
  odd: [1, 7, 37, ...],
  odd: [42, 2, ...],
}

Slow solution

function slow_solution(integers) {
  return integers.reduce(
    ({ odd, even }, n) => {
      if (n % 2 === 0) return { odd, even: [...even, n] };
      return { odd: [...odd, n], even };
    },
    { odd: [], even: [] }
  );
}

Why is this slow?

We are creating a new array and new object on each iteration of the reduce callback.

Faster reduce solution

function faster_reduce_solution(integers) {
  return integers.reduce(
    (res, n) => {
      if (n % 2 === 0) res.even.push(n);
      else res.odd.push(n);
      return res;
    },
    { odd: [], even: [] }
  );
}

Why is that faster?

This mutates the arrays instead of creating new ones. So we avoided creating unneeded objects successfully.

Alternative solution without mutation

if your coding style forces you not to mutate variables. You can avoid using .reduce and use .filter instead. Which is cleaner in my opinion:

function faster_filter_solution(integers) {
  return {
    odd: integers.filter((n) => n % 2 === 1),
    even: integers.filter((n) => n % 2 === 0),
  };
}

Benchmark

slow_solutionfaster_reduce_solutionfaster_filter_solution
1k integers5.216 ms0.247 ms0.215 ms
10k integers57.073 ms0.541 ms0.638 ms
100k integers27299.561 ms3.823 ms2.969 ms

Benchmark run on Github actions