DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 101

The task is to implement a browser history.

The boilerplate code

class BrowserHistory {

  /**
   * @param {string} url
   * if url is set, it means new tab with url
   * otherwise, it is empty new tab
   */
  constructor(url) {

  }
  /**
   * @param { string } url
   */
  visit(url) {

  }

  /**
   * @return {string} current url
   */
  get current() {

  }

  // go to previous entry
  goBack() {

  }

  // go to next visited url
  forward() {

  }
}
Enter fullscreen mode Exit fullscreen mode

Store visited urls, have a pointer to the current page and store how the tab is created.

this.history = [];
this.index = -1;
this.hasInitialUrl = Boolean(url)
Enter fullscreen mode Exit fullscreen mode

The initial index being -1 means that the tab is empty, no page is loaded. If a page is loaded, store it in the history array

 if (url) {
    this.history.push(url);
    this.index = 0;
  }
Enter fullscreen mode Exit fullscreen mode

When a new url is visited, it is stored and the index is increased.

visit(url) {
  this.history = this.history.slice(0, this.index + 1);
  this.history.push(url);
  this.index++;
}

Enter fullscreen mode Exit fullscreen mode

It is sliced because, if you visit A => B => C, then go back to B and visit D, history must go back to B from D, like a real browser.

To get the current URL

get current() {
  return this.index >= 0 ? this.history[this.index] : undefined;
}
Enter fullscreen mode Exit fullscreen mode

To go back, also consider the initial url and not go back beyond that if the tab was not empty on first view

goBack() {
  if (this.hasInitialUrl) {
    if (this.index > 0) {
      this.index--;
    }
  } else {
    if (this.index >= 0) {
      this.index--;
    }
  }
  return this.current;
}
Enter fullscreen mode Exit fullscreen mode

To move forward, ensure that a future page exists

forward() {
  if (this.index < this.history.length - 1) {
    this.index++;
  }
  return this.current;
}
Enter fullscreen mode Exit fullscreen mode

The final code

class BrowserHistory {

  constructor(url) {
    this.history = [];
    this.index = -1;
    this.hasInitialUrl = Boolean(url)

    if(url) {
      this.history.push(url);
      this.index = 0;
    }
  }

  visit(url) {
    this.history = this.history.slice(0, this.index + 1);

    this.history.push(url);
    this.index++;
  }

  get current() {
    return this.history[this.index] || undefined;
  }


  goBack() {
    if(this.hasInitialUrl) {
      if(this.index > 0) {
        this.index--;
      }
    } else {
      if(this.index >= 0) {
        this.index--;
      }
    }
    return this.current
  }

  forward() {
    if(this.index < this.history.length - 1) {
      this.index++;
    }
    return this.current;
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)