DEV Community

myleftshoe
myleftshoe

Posted on

Modern JS

Private class properties, getters, iterators in one simple example

Ever needed to loop over a set of values continuously, i.e. return to the first value when the end is reached? You could use an array, increment the index and set it to 0 when the end is reached, or you could take the opportunity to learn some modern js features:

class Looper {
    #i // iterator
    #b // iterable e.g. array, Map, Set
    #v // value 
    constructor(iterable) {
        this.#b = iterable
        this.reset()
    }
    get value() {
        return this.#v.value
    }
    get next() {
        this.#v = this.#i.next()
        if (this.#v.done) {
            this.reset()
        }
        return this.value
    }
    reset() {
        this.#i = this.#b[Symbol.iterator]()
        this.#v = this.#i.next() 
        return this
    }
}
Enter fullscreen mode Exit fullscreen mode

Example usage:

const loop = new Looper([1,2,3])
loop.value //1
loop.next //2
loop.next //3
loop.next //1
loop.next //2
loop.reset()
loop.value //1
loop.next //2
loop.reset().value //1
loop.next //2
loop.next //3
Enter fullscreen mode Exit fullscreen mode

:)

Top comments (0)