Created
April 10, 2021 15:34
-
-
Save kayac-chang/0b63699d23ba18e45ce91a064cdf99d5 to your computer and use it in GitHub Desktop.
JS curcular function
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
// input: min=2, max=4, value=-1 | |
// return 2 | |
// input: min=2, max=4, value=0 | |
// return 3 | |
// input: min=2, max=4, value=1 | |
// return 4 | |
// input: min=2, max=4, value=2 | |
// return 2 | |
// input: min=2, max=4, value=3 | |
// return 3 | |
// input: min=2, max=4, value=4 | |
// return 4 | |
// input: min=2, max=4, value=5 | |
// return 2 | |
// input: min=2, max=4, value=6 | |
// return 3 | |
function mod(max, value) { | |
return ((value % max) + max) % max; | |
} | |
function circular(min, max, value) { | |
return mod(max - min + 1, value - min) + min; | |
} | |
function main() { | |
[ | |
[2, 4, -1, 2], | |
[2, 4, 0, 3], | |
[2, 4, 1, 4], | |
[2, 4, 2, 2], | |
[2, 4, 3, 3], | |
[2, 4, 4, 4], | |
[2, 4, 5, 2], | |
[2, 4, 6, 3] | |
].forEach(([min, max, value, ans]) => { | |
console.log([min, max, value, ans], ans, circular(min, max, value)); | |
console.assert(ans === circular(min, max, value), `not passing!!!`); | |
}); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment