Created
February 14, 2020 05:16
-
-
Save bas080/7b32c7bba0949f6cdc39ce08e28e4179 to your computer and use it in GitHub Desktop.
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
const assert = require('assert') | |
class Playlist { | |
constructor(items) { | |
this.__items = items | |
this.__index = 0 | |
} | |
isLastItem() { | |
return (this.__index === this.__items.length - 1) | |
} | |
isFirstItem() { | |
return (this.__index === 0) | |
} | |
current() { | |
return this.__items[this.__index] | |
} | |
outOfRange(index) { | |
return index < 0 || index >= this.__items.length | |
} | |
setCurrent(index) { | |
if (this.outOfRange(index)) | |
throw new Error('Out of range') | |
return this.__index = index | |
} | |
next() { | |
if (this.isLastItem()) | |
this.__index = 0 | |
else | |
this.__index = this.__index + 1 | |
return this | |
} | |
previous() { | |
if (this.isFirstItem()) | |
this.__index = this.__items.length | |
else | |
this.__index = this.__index - 1 | |
return this | |
} | |
} | |
const playlist = new Playlist(['a', 'b', 'c']) | |
assert.equal(playlist.current(), 'a') | |
playlist.next() | |
assert.equal(playlist.current(), 'b') | |
assert.equal(playlist.next().current(), 'c') | |
playlist.setCurrent(0) | |
playlist.setCurrent(2) | |
try { | |
playlist.setCurrent(-1) | |
} catch (err) { | |
assert.equal(err.message, 'Out of range') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment