Wednesday, January 23, 2019

Recursive map

let map = (fn,list) => !list.length ? []:
  [fn(list[0])].concat(map(fn,list.slice(1)));
1
map(x=>x+1,[1,2,3,4)) // => [2,3,4,5]


Another way using spread operator

map = (fn, [head, ...tail]) => (
 head === undefined ? [] : [fn(head), ...map(fn, tail)]
);

No comments:

Followers

Link