Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Created August 20, 2024 18:17
Show Gist options
  • Save yongjhih/58361a862bff51709dfd4701fbdc9aa2 to your computer and use it in GitHub Desktop.
Save yongjhih/58361a862bff51709dfd4701fbdc9aa2 to your computer and use it in GitHub Desktop.
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