Created
March 5, 2019 13:10
-
-
Save artalar/8cf38785cc152d6d3c8b889b07c36929 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ArrayLazy extends Array { | |
| _lazyQueue = []; | |
| map(callback) { | |
| this._lazyQueue.push({ type: "map", callback }); | |
| return this; | |
| } | |
| filter(callback) { | |
| this._lazyQueue.push({ type: "filter", callback }); | |
| return this; | |
| } | |
| collect() { | |
| const result = new ArrayLazy(); | |
| collect: for (let i = 0; i < this.length; i++) { | |
| let value = this[i]; | |
| for (let j = 0; j < this._lazyQueue.length; j++) { | |
| const { type, callback } = this._lazyQueue[j]; | |
| if (type === "filter") { | |
| if (!callback(value)) continue collect; | |
| } else { | |
| // map | |
| value = callback(value); | |
| } | |
| } | |
| result.push(value); | |
| } | |
| this._lazyQueue = []; | |
| return result; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment