要求:
- 支持鏈式調用,如:_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]