Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Created September 1, 2021 08:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirkaufman/09374432830538f94954e3c768b37e74 to your computer and use it in GitHub Desktop.
Save nirkaufman/09374432830538f94954e3c768b37e74 to your computer and use it in GitHub Desktop.
/*******************
warm up
*******************/
function* generateAlphaBet() {
let i = "a".charCodeAt(0);
let end = "z".charCodeAt(0) + 1;
while(i < end) {
yield String.fromCharCode(i);
i++;
}
}
// destructure like a Boss
const {0: first, length, [length-1]: last} = [...generateAlphaBet()];
console.log(first); // -> a
console.log(last); // -> b
/*******************
transform streams with generators
*******************/
function* transform(iterable, tFn) {
for(const v of iterable) {
yield tFn(v)
}
}
function* map(iterable, mapFn) {
yield* transform(iterable, mapFn)
}
const users = [
{ fName: 'nir', lName: 'kaufman'},
{ fName: 'udi', lName: 'mazor'},
{ fName: 'Yaniv', lName: 'falik'},
]
// MOD === Map On Damned!
const MOD = map(users, user => ({ name: `${user.fName} ${user.lName}` }))
// Map one after each other
console.log(MOD.next().value);
console.log(MOD.next().value);
console.log(MOD.next().value);
// Push new users
users.push({ fName: 'nitsan', lName: 'zohar' });
// continue
console.log(MOD.next().value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment