Simple History

by João Vitor Scheuermann

HTML

<div>
   
  
</div>

JavaScript

class History {
	constructor () {
  	this.states = []
    this.index = null
  }
  
  add (state) {
    let hasHistory = this.index !== null
    let maxIndex = this.states.length - 1
    
    if (hasHistory && this.index !== maxIndex) {
			this.states.splice(this.index + 1, maxIndex)
    }
		
    this.states.push(state)
    this.index = this.states.length - 1
  }
  
  forward () {
  	let maxIndex = this.states.length - 1
  	if (this.index < maxIndex) this.index++
  }
  
  back () {
  	this.index--
  }
  
  get state () {
  	return this.states[this.index] || null
  }
}

let history = new History()

history.add({a: 'a'}) // 0
history.add({b: 'b'}) // 1
history.add({c: 'c'}) // 2
history.add({d: 'd'}) // 3

history.back() // 3
history.back() // 2
history.back() // 1
history.back() // 0

history.forward() // 1
history.forward() // 2

history.add({e: 'e'})

console.log(history.state)

console.log(history)