模拟js中的map/filter/reduce

208 阅读1分钟

map

const fakeMap = (list, fn) => {
  let res = []
  for (let i = 0; i < list.length; i++) {
    res.push(fn(list[i]));
  }
  return res;
}

const list = [1, 2, 3, 4];
const f1 = x => x * x;
fakeMap(list, f1); // [ 1, 4, 9, 16 ]

filter

const fakeFilter = (list, fn) => {
  let res = []
  for (let i = 0; i < list.length; i++) {
    const ele = list[i];
    if (fn(ele)) {
      res.push(ele)
    }
  }
  return res;
}
const list = [1, 2, 3, 4];
const f2 = x => x > 2;
fakeFilter(list, f2); // [ 3, 4 ]

reduce

const fakeReduce = (list, fn, init) => {
  let res = list[0], j = 1;
  init && (res = init) && (j = 0);
  for (let i = j; i < list.length; i++) {
    res = fn(res, list[i], i, list);
  }
  return res;
}
const list = [1, 2, 3, 4];
const reducer = (acc, cur) => acc + cur;
fakeReduce(list, reducer); // 10
fakeReduce(list, reducer, 10); // 20