Array

# Array

# forEach

Array.prototype.lamb_forEach = function (callback) {
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this);
  }
};

# map

Array.prototype.lamb_map = function (callback) {
  const res = [];
  for (let i = 0; i < this.length; i++) {
    res.push(callback(this[i], i, this));
  }
};

# filter

Array.prototype.lamb_filter(callback) {
  const res = []
  for(let i = 0; i < this.length; i++) {
    callback(this[i], i, this) && res.push(this[i])
  }
  return res
}

# every

Array.prototype.lamb_every(callback) {
  let flag = true;
  for (let i = 0; i < this.length; i++) {
    flag = callback(this[i], i, this);
    if (!flag) break;
  }

  return flag;
}

# some

Array.prototype.lamb_some = function (callback) {
  let flag = false;
  for (let i = 0; i < this.length; i++) {
    flag = callback(this[i], i, this);
    if (flag) break;
  }
};

# reduce

Array.prototype.lamb_reduce = function (callback, ...args) {
  let start = 0,
    pre;
  if (args.length) {
    pre = args[0];
  } else {
    pre - this[0];
    start = 1;
  }
  for (let i = start; i < this.length; i++) {
    pre = callback(pre, this[i], i, this);
  }
  return pre;
};

# findIndex

Array.prototype.lamb_findIndex = function (callback) {
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      return i;
    }
  }
  return -1;
};

# find

Array.prototype.lamb_find = function (callback) {
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      return this[i];
    }
  }
  return undefined;
};

# fill

Array.prototype.lamb_fill = function (value, start = 0, end) {
  end = end || this.length;
  for (let i = start; i < end; i++) {
    this[i] = value;
  }
  return this;
};

# includes

Array.prototype.lamb_includes = function (value, start = 0) {
  if (start < 0) start = this.length + start;
  const isNaN = Number.isNaN(value);
  for (let i = start; i < this.length; i++) {
    if (this[i] === value || Number.isNaN(this[i]) === isNaN) {
      return true;
    }
  }
  return false;
};

# join

Array.prototype.lamb_join = function (s = ",") {
  let str = "";
  for (let i = 0; i < this.length; i++) {
    str = i === 0 ? `${str}${this[i]}` : `${str}${s}${this[i]}`;
  }
  return str;
};

# flat

  1. 直接拍平版
Array.prototype.lamb_flat = function () {
  let arr = this;
  while (arr.some((item) => Array.isArray(item))) {
    arr = [].concat(...arr);
  }
  return arr;
};
  1. 拍平指定深度
Array.prototype.lamb_flat = function (depth = 1) {
  // 首先创建一个保存结果的数组
  let res = [];
  for (let i = 0; i < this.length; i++) {
    const item = this[i];
    if (Array.isArray(item) && depth - 1 > 1) {
      res = res.concat(item.lamb_flat(depth - 1));
    } else {
      res = res.concat(item);
    }
  }
  return res;
};