-1

I've following two different approaches and confused on which one is recommended and why in terms of readability and memory allocation. As per my understanding both are same in terms of space complexity both(two variables in first approach and accumulator in reduce method) takes space. Which approach is recommended?

Approach 1:

const getFilters = () => {
  const filters1 = [];
  const filters2 = [];
  // assume filters is an array of numbers
  filters.forEach(filter => {
    if(filter === 1) {
      filters1.push(filter);
    } else {
      filters2.push(filter);
    }
  })
  return {
    filter1,
    filter2,
  }
}

Approach 2:

const getFilters = () => {
  // assume filters is an array of numbers
  return filters.reduce(
    (accumulator, filter) => {
      if (filter === 1) {
        accumulator.filters1.push(filter);
      } else {
        accumulator.filters2.push(filter);
      }
    },
    {
      filters1: [],
      filters2: [],
    },
  );
}
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
  • *"Which one would you prefer to do and why?"*: questions about preferences are off topic here. – trincot Nov 04 '22 at 06:49
  • 1
    In terms of space complexity, these look exactly the same to me. The two arrays are in the same object in Approach 2 but I don't see this changing anything. There isn't much difference in readability, either, except that semantically this isn't really reducing/accumulating anything so I would prefer the other approach – Codebling Nov 04 '22 at 06:58
  • "which approach is recommended" is not really any different from "which one do you prefer". Is there an *objective* metric you are interested in? – TylerH Nov 04 '22 at 13:53

1 Answers1

1

Both approaches are the same in both space and time complexity. However, your reduce example would throw an error since you must return the accumulator after each iteration.

reduce() is a central concept in functional programming, where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's reduce(): you should use spreading or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined.

MSDN Article

And to answer the question in your title, yes, accumulator takes space in memory. An accumulator is just a variable (array in your case) that gets passed as an argument.

Fralle
  • 889
  • 6
  • 12