Created
July 13, 2019 08:52
-
-
Save ungarson/80060f10b428a3200f6913bc2b535a1f to your computer and use it in GitHub Desktop.
Passing an argument to a generator function in example of generating IDs
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
export default function* idGeneration(start = 0) { | |
while(true) { | |
const newID = yield start++; | |
if (typeof newID !== 'undefined') { | |
start = newID; | |
yield start++; | |
} | |
} | |
} | |
// Example of usage | |
// const idGenerator = idGeneration(); | |
// console.log(idGenerator.next().value); // 0 | |
// console.log(idGenerator.next().value); // 1 | |
// console.log(idGenerator.next().value); // 2 | |
// console.log(idGenerator.next(5).value); // 5 | |
// console.log(idGenerator.next().value); // 6 | |
// console.log(idGenerator.next().value); // 7 | |
// console.log(idGenerator.next(100).value); // 100 | |
// console.log(idGenerator.next().value); // 101 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment