要求:
- 支持链式调用,如:_chain(data).map().filter().value()
- 实现map、filter、等常用方法
- 支持惰性求值(延迟执行、直到用到value()时才真正计算)。
链式调用的实现原理的关键点是:函数执行完以后,返回它自身,也就是执行完之后返回this。具体代码如下:
class Chain {constructor(data) {this.data = data;this.array = []}map(fn){this.array.push({key: 'map',fn,})return this;}filter(fn){this.array.push({key: 'filter',fn,})return this;}reduce(fn){this.array.push({key: 'reduce',fn,})return this;}value () {this.array.forEach(item => {this.data = this.data[item.key](item.fn)})return this.data;}}const arr = [1, 2, 3, 4]const result = new Chain(arr).map(x => x * 2).filter(x => x > 4).value()console.log('执行结果:', result);// [6, 8]