手写算法: 满足三条件之一需改变的最少字符数

1737. 满足三条件之一需改变的最少字符数open in new window

看不懂答案,放弃了

// TODO: 以后再做

答案open in new window

思路

手写题: 实现 Array.prototype.reduce()

146. implement Array.prototype.reduce()open in new window

主要验证几个点

  1. 数组为空时,没有初始值,抛出错误 Expected function to throw an exception
  2. 数组为空时,有初始值,返回初始值
Array.prototype.myReduce = function(callback, initialValue) {
  if (typeof callback !== 'function') {
    throw new TypeError(`expect got function, but got ${typeof callback}`);
  }

  if (!Array.isArray(this)) {
    throw new TypeError(`expect got an array, but got ${typeof this}`);
  }

  const arr = this,
    argLen = arguments.length,
    len = arr.length;

  // 数组为空且初始值未提供,抛出异常
  if (!len && argLen === 1) {
    throw new TypeError();
  }

  let accumulator = argLen === 1 ? arr[0] : initialValue,
    index = argLen === 1 ? 1 : 0;

  for (let i = index; i < len; i++) {
    accumulator = callback(accumulator, arr[i], i, arr);
  }
  return accumulator;
};
Last Updated:
Contributors: kk