map, filter, reduce, call, apply, bind 내장 메소드 구현

Taek·2021년 5월 8일
0

map

Array.prototype.myMap = function (callback, thisArg) {
  const mapArray = [];
  for (let i = 0; i < this.length; i++) {
    const mapValue = callback.call(thisArg || window, this[i], i, this);
    mapArray[i] = mapValue;
  }
  return mapArray;
};

filter

Array.prototype.myFilter = function (callback, thisArg) {
  const filterArray = [];
  for (let i = 0; i < this.length; i++) {
    const isFiltering = callback.call(thisArg || window, this[i], i, this);
    if (isFiltering) filterArray.push(this[i]);
  }
  return filterArray;
};

reduce

Array.prototype.myReduce = function (callback, initialValue) {
  let accumulateValue = initialValue || this.shift();
  this.forEach((currentValue) => {
    accumulateValue = callback(accumulateValue, currentValue);
  });
  return accumulateValue;
};

call

Function.prototype.myCall = function (thisArg, ...args) {
    thisArg.fn = this;
    thisArg.fn(...args);
    delete thisArg.fn;
};

apply

Function.prototype.myApply = function (thisArg, argArr) {
    thisArg.fn = this;
    thisArg.fn(...argArr);
    delete thisArg.fn;
};

bind

Function.prototype.myBind = function (thisArg, ...args) {
  return (..._args) => this.call(thisArg, ...[...args, ..._args]);
};

0개의 댓글