Search

1/22/2015

Functional Programming in Javascript === Garbage « Thomas Reynolds

Functional Programming in Javascript === Garbage « Thomas Reynolds

These can both be written as a reducer.
function map(f, list) {
  return reduce(function(val, sum) {
    sum.push(f(val));
    return sum;
  }, list, []);
}
The reducer takes a function which can update a value sum which starts at [] and is updated once for each item in the list. Okay, that was a long lead in. Here's how you could naively implement a reducer:
function reduce(f, list, sum) {
  if (list.length < 1) {
    return sum;
  } else {
    var val = list.shift();
    return reduce(f, list, f(val, list));
  }
}

沒有留言: