Skip to content

Instantly share code, notes, and snippets.

@horiuchie
Created December 11, 2019 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save horiuchie/976592cb00f71db0ee327d55bd5794ca to your computer and use it in GitHub Desktop.
Save horiuchie/976592cb00f71db0ee327d55bd5794ca to your computer and use it in GitHub Desktop.
Infinite counter on Javascript
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