serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

简单实现浏览器history #1

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

题目

与浏览器history相关的常见操作: new BrowserHistory() - 当你打开一个新标签时,它被设置为一个空的历史记录 goBack() - 回到上一个标签,同时还应该能使用forward()前进 forward() - 回到下一个访问过的标签页 visit() - 当你输入新地址或单击链接时,会添加一个记录,但同时会截断前面所有访问过的记录(截断所有forward()方法可以到达的标签)

例子

const bh = new BrowserHistory()
bh.visit('A')
bh.visit('B')
bh.visit('C')
bh.goBack()  // bh.current: B
bh.visit('D')  // bh.current: D
bh.forward() // bh.current: D

回答

class BrowserHistory {

  /**
   * @param {string} url
   * if url is set, it means new tab with url
   * otherwise, it is empty new tab
   */
  constructor(url) {
    this.queue=[]
    //当前current位置
    this.currentIndex=0
    if(url !== undefined){
        this.queue.push(url)
    }
  }
  /**
   * @param { string } url
   */
  visit(url) {
    //截断currentIndex后面的记录
    this.queue.length = this.currentIndex+1
    this.queue.push(url)
    this.currentIndex += 1
  }

  /**
   * @return {string} current url
   */
  get current() {
    return this.queue[this.currentIndex]
  }

  // go to previous entry
  goBack() {
    this.currentIndex=Math.max(0,this.currentIndex-1)
  }

  // go to next visited url
  forward() {
    this.currentIndex=Math.min(this.queue.length-1,this.currentIndex+1)
  }
}