Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Created December 28, 2021 18:37
Show Gist options
  • Save mitchallen/fcfed13dc1c799bbbab6568c7cc6e655 to your computer and use it in GitHub Desktop.
Save mitchallen/fcfed13dc1c799bbbab6568c7cc6e655 to your computer and use it in GitHub Desktop.
Zero Based Counter that Wraps
function createZeroBasedCounter( options = {} ) {
// zero based
// increment automatically wraps
let {
cursor = 0,
limit = 5, // [0..(limit -1)]
} = options;
let increment = () => cursor < limit - 1 ? ++cursor : cursor = 0;
return {
get value() { return cursor },
increment,
}
}
let counter = createZeroBasedCounter( {limit: 3});
for( let i = 0; i < 10; i++ ) {
let a = counter.value;
let b = counter.increment();
console.log(`value: ${a}, => increment: ${b}`);
}
/*
value: 0, => increment: 1
value: 1, => increment: 2
value: 2, => increment: 0
value: 0, => increment: 1
value: 1, => increment: 2
value: 2, => increment: 0
value: 0, => increment: 1
value: 1, => increment: 2
value: 2, => increment: 0
value: 0, => increment: 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment