面试官:请实现一个数组工具类,并支持链式调用。

116 阅读1分钟
class ArrayTools {
  value;

  constructor(arr) {
    if (!Array.isArray(arr)) {
      throw new Error("请传入数组!");
    }
    this.value = arr.slice(0);
  }

  map(cb) {
    const list = [];
    for (let i = 0; i < this.value.length; i++) {
      list[i] = cb(this.value[i], i, this.value);
    }
    this.value = list;
    return this;
  }

  filter(cb) {
    const list = [];
    for (let i = 0; i < this.value.length; i++) {
      if (cb(this.value[i], i, this.value)) {
        list.push(this.value[i]);
      }
    }
    this.value = list;
    return this;
  }

  sortBy(key) {
    this.value.sort((p, n) => {
      return (+p[key]) - (+n[key])
    });
    
    return this
  }
  
  reverse() {
    this.value.reverse()
    return this
  }

  formatArrayTo2LayerArray( num) {
    const list = [];
    for (var i = 0; i < this.value.length; i += num) {
      list.push(this.value.slice(i, i + num));
    }
    this.value = list
    return this
  }

  /** 调用返回数据 */
  execute() {
    return this.value;
  }

}

const arrayTools = new ArrayTools([
  { id: 1, label: "1" },
  { id: 4, label: "4" },
  { id: 2, label: "2" },
  { id: 3, label: "3" },
  { id: 5, label: "5" },
  { id: 6, label: "6" },
  { id: 7, label: "7" },
  { id: 8, label: "8" },
]);

const result = arrayTools
  .map((item) => ({ ...item, label: item.label + "-map" }))
  .filter((item) => item.id >= 2)
  .sortBy('id')
  .reverse()
  .formatArrayTo2LayerArray(4)
  .execute();
  
console.log("result", result);

总结:这块只实现了一些基本的数组方法,并没有做性能,错误处理,单纯为了实现其功能。其核心点就是每个函数返回this。