Created
August 20, 2024 18:17
-
-
Save yongjhih/58361a862bff51709dfd4701fbdc9aa2 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
const Generator = Object.getPrototypeOf(function* () { }); | |
Generator.prototype.map = function* (mapper) { | |
for (const it of this) { | |
yield mapper(it); | |
} | |
}; | |
Generator.prototype.filter = function* (predicate) { | |
for (const it of this) { | |
if (predicate(it)) yield it; | |
} | |
}; | |
Generator.prototype.take = function* (n) { | |
let i = 0; | |
for (const it of this) { | |
if (i >= n) break; | |
yield it; | |
i++; | |
} | |
}; | |
Generator.prototype.toList = () => Array.from(this); | |
/// aka toList()[0] | |
Generator.prototype.first = function (n) { | |
const it = toList(); | |
return it ? it[0] : null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment