DEV Community

Cover image for Implement browser history
Sumit Upadhyay
Sumit Upadhyay

Posted on

Implement browser history

Problem Statement -

You must be familiar with browser history and its functionality where you can navigate through the browsed history. Implement the same.

It will have the following functionality

visit(url): Marks the entry of the URL in the history.
● current(): Returns the URL of the current page.
● backward(): Navigate to the previous url.
● forward(): Navigate to the next url.

Example

Input:
const bh = new BrowserHistory();
bh.visit('A');
console.log(bh.current());
bh.visit('B');
console.log(bh.current());
bh.visit('C');
console.log(bh.current());
bh.goBack();
console.log(bh.current());
bh.visit('D');
console.log(bh.current());
Output:
"A"
"B"
"C"
"B"
"D"


Enter fullscreen mode Exit fullscreen mode

We can implement this with the help of an array and index tracker for navigation.

For each visit, add the URL at the next index. while navigating backward return the URL of the previous index, going forward return the URL at the next index. Add checks to prevent the under and overflowing of the indexes.

function BrowserHistory() {
  // track history
  this.history = [];
  this.index = -1;
  // add new url at next index
  this.visit = function(url){
    this.history[++this.index] = url;
}
  // return the url of the current index
  this.current = function() {
    return this.history[this.index];
}
  // go to previous entry
  this.backward = function() {
     this.index = Math.max(0, --this.index);
}
  // go to next entry
  this.forward = function() {
     this.index = Math.min(this.history.length - 1, ++this.index);
} }
Enter fullscreen mode Exit fullscreen mode

Test Case

Input:
const bh = new BrowserHistory();
bh.visit('A');
console.log(bh.current());
bh.visit('B');
console.log(bh.current());
bh.visit('C');
console.log(bh.current());
bh.backward();
console.log(bh.current());
bh.visit('D');
console.log(bh.current());
bh.backward();
console.log(bh.current());
bh.forward();
console.log(bh.current());
Output:
"A"
"B"
"C"
"B"
"D"
"B"
"D"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)