Accumulator: Three ways to write the filter function.

Accumulator: Three ways to write the filter function.

2019, Sep 09    

Accumulator a new thing for me that I just learned from coursera course: Programming Languages, Part A. Let’s take one easy example function to understand the idea of accumulator.

filter1(): use a loop

// use loop
const filter1 = (f, list) => {
  if (!list) return list;
  const res = [];
  list.forEach(num => {
    if (f(num)) {
      res.push(num);
    }
  });
  return res;
}

filter2(): use recursion

// use recursion
const filter2 = (f, list) => {
  if (list.length === 0) {
    return [];
  }
  const first = list[0];
  if (f(first)) {
    return [first, ...filter2(f, list.slice(1))];
  }
  return filter2(f, list.slice(1));
}

filter3(): use recursion with accumulator

// use recursion with accumulator
const filter3 = (f, list, acc) => {
  if (list.length === 0) {
    return acc;
  }
  const first = list[0];
  if (f(first)) {
    acc.push(first);
    
  }
  return filter2(f, list.slice(1),acc);
}
const res1 = filter1(x => x > 0, [-1,0,1,2,3]);
const res2 = filter2(x => x > 0, [-1,0,1,2,3]);
const res3 = filter3(x => x > 0, [-1,0,1,2,3], []);

result:

console.log(res1);
console.log(res2);
console.log(res3);
// [1,2,3]
// [1,2,3]
// [1,2,3]

reduce() in JavaScript

Refrences

Programming Languages, Part A