ES6中一些高阶函数的代码实现

前提

以下方法在其数组元素被删除/未被初始化时不调用回调函数。

使用索引 in 数组的方式判断数组元素是否是被删除/未被初始化的状态

forEach

Array.prototype._forEach = function (callback, thisArg) {
    const arrLen = this.length;
    let i = 0;
    while(i < arrLen) {
        // 被删除/未被初始化的元素不循环
        if (i in this) {
	        callback.call(thisArg, this[i], i, this);
        }
        i++;
    }
}

filter

Array.prototype._filter = function (callback, thisArg) {
    const res = [],
          arrLen = this.length;
    let i = 0;
    while (i < arrLen) {
        if (i in this) {
            const value = this[i];
            callback.call(thisArg, value, i, this) && res.push(value);
        }
        i++;
    }
    return res;
}

map

原生实现

Array.prototype._map = function (callback, thisArg) {
    const res = [],
          arrLen = this.length;
    let i = 0;
    while(i < arrLen) {
        if (i in this) {
            res[i] = callback.call(thisArg, this[i], i, this);
        }
        i++;
    }
    return res;
}

reduce实现

Array.prototype._map = function (callback, thisArg) {
    return this.reduce((arr, value, index, array) => {
        arr[index] = callback.call(thisArg, value, index, array);
    }, []);
}

some

Array.prototype._some = function (callback, thisArg) {
    let i = 0;
    const arrLen = this.length;
    while (i < arrLen) {
        if (i in this) {
            if (callback.call(thisArg, this[i], i, this)) {
                return true;
            }
        }
        i++;
    }
    return false;
}

every

Array.prototype._every = function (callback, thisArg) {
    let i = 0,
        loopCount = 0,
        trueCount = 0;
    const arrLen = this.length;
    while (i < arrLen) {
        if (i in this) {
            loopCount++;
            if (callback.call(thisArg, this[i], i, this)) {
                trueCount++;
            }
        }
        i++;
    }
    return loopCount === trueCount;
}

reduce

Array.prototype._reduce = function (...args) {
  const arrLen = this.length;
  if (args.length === 1 && !arrLen) {
    throw new TypeError('Reduce of empty array with no initial value')
  }

  const callback = args[0];
  let initialValue = this[0],
      i = 1;
  if (args.length > 1) {
      initialValue = args[1];
      i--;
  }
  let accumulator = initialValue;
  while (i < arrLen) {
      if (i in this) {
          accumulator = callback(accumulator, this[i], i, this);
      }
      i++;
  }
  return accumulator;
} 
posted @ 2021-12-19 21:37  酉云良  阅读(39)  评论(0)    收藏  举报