Skip to content

Instantly share code, notes, and snippets.

@kesava
Created December 15, 2022 21:08
Show Gist options
  • Save kesava/a989adb07710ba0649ea867f2e30b93e to your computer and use it in GitHub Desktop.
Save kesava/a989adb07710ba0649ea867f2e30b93e to your computer and use it in GitHub Desktop.
Generators talk as part of UI Lunch and Learn 12/15/2022
// Generators
const obj = {
a: 1,
b: 2,
c: 3,
};
obj[Symbol.iterator] = function *() {
for(const k of Object.keys(obj)) {
yield [k, obj[k]]
}
};
const iterObj = Object.keys(obj).map(x => [x, obj[x]]);
[...obj]
function* naturalNumbers() {
for (let n=0;; n++) {
yield n;
}
}
// const aa = naturalNumbers()
const [a, b, c] = naturalNumbers();
console.log({ a, b, c })
const squaredInts = function *() {
let i = 1;
while (true) {
yield i * i;
i += 1;
}
}
const [d, e, f, g, h, i] = squaredInts();
console.log({ d, e, f, g, h, i});
function* take(n, iterable) {
for (const x of iterable) {
if (n <= 0) return;
n--;
yield x;
}
}
// function sumOfSquared(bound) {
// const sqs = squaredInts();
// let acc = 0;
// for(const sq of sqs) {
// // console.log({ sq })
// acc += sq;
// if (acc > bound) return acc;
// }
// }
[...take(29, naturalNumbers())]
// sumOfSquared(33)
const str = 'Hello! this is @kesava demonstrating @javascript';
const usernameRegex = new RegExp(/@(\w+)/, 'g');
function *getUsernames(str) {
let match = null;
do {
match = usernameRegex.exec(str);
if (match) {
yield match;
}
} while (match);
}
[...getUsernames(str)]
class BinaryTree {
constructor(value, left=null, right=null) {
this.value = value;
this.left = left;
this.right = right;
}
* [Symbol.iterator]() {
if (this.left) {
yield* this.left
}
yield this.value;
if (this.right) {
yield* this.right;
}
}
}
const tree = new BinaryTree(3, new BinaryTree(2), new BinaryTree(9, new BinaryTree(7), new BinaryTree(11)));
[...tree]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment