Skip to content

Instantly share code, notes, and snippets.

@caderek
Last active February 7, 2023 20:20
Show Gist options
  • Save caderek/b69d1d03781ef91608a68af30ddc2760 to your computer and use it in GitHub Desktop.
Save caderek/b69d1d03781ef91608a68af30ddc2760 to your computer and use it in GitHub Desktop.
Modular arithmetic example
// JS remainder operator `%` won't work for our case,
// we need a modulo that follows modular arithmetics definition.
function mod(num, modulus) {
return ((num % modulus) + modulus) % modulus;
}
// Alternative (not strict, but IMO easier to remember)
function modAlt(num, modulus) {
const x = num % modulus;
return x < 0 ? x + modulus : x;
}
/* Example usage */
class Playlist {
#songs;
#index = 0;
constructor(songs) {
this.#songs = songs;
}
get current() {
return this.#songs[this.#index];
}
offsetBy(num) {
this.#index = mod(this.#index + num, this.#songs.length);
return this.current;
}
next() {
return this.offsetBy(1);
}
prev() {
return this.offsetBy(-1);
}
}
const playlist = new Playlist(["song_1.mp3", "song_2.mp3", "song_3.mp3"]);
console.log(playlist.current); // song_1.mp3
console.log(playlist.offsetBy(2)); // song_3.mp3
console.log(playlist.next()); // song_1.mp3
console.log(playlist.prev()); // song_3.mp3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment