Created
December 28, 2021 18:37
-
-
Save mitchallen/fcfed13dc1c799bbbab6568c7cc6e655 to your computer and use it in GitHub Desktop.
Zero Based Counter that Wraps
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
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