Created
December 11, 2019 08:08
-
-
Save horiuchie/976592cb00f71db0ee327d55bd5794ca to your computer and use it in GitHub Desktop.
Infinite counter on Javascript
This file contains 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
function infiniteCounter (start=0, step=1) { | |
const iter = function* () { | |
let counts = start; | |
while (true) { | |
// console.log({ message: counts }); | |
yield counts; | |
counts += step; | |
} | |
}(); | |
return () => iter.next().value; | |
}; | |
// Usage | |
const generateId = infiniteCounter(); | |
console.log( generateId()); // 0 | |
console.log( generateId()); // 1 | |
console.log( generateId()); // 2 | |
const generateOdd = infiniteCounter(1, 2); | |
console.log( generateOdd() ); // 1 | |
console.log( generateOdd() ); // 3 | |
console.log( generateOdd() ); // 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment