AlgoDaily Solution

1// BrowserHistory class definition
2class BrowserHistory {
3    constructor(url) {
4        this.history = [];
5        this.pointer = -1;
6        if (url !== undefined) {
7            this.history.push(url);
8            this.pointer++;
9        }
10    }
11
12    visit(url) {
13        this.history = this.history.slice(0, this.pointer + 1);
14        this.history.push(url);
15        this.pointer++;
16    }
17
18    back() {
19        this.pointer = Math.max(0, --this.pointer);
20        return this.history[this.pointer];
21    }
22
23    forward() {
24        this.pointer = Math.min(this.history.length - 1, ++this.pointer);
25        return this.history[this.pointer];
26    }
27}
28
29// Driver code to test the BrowserHistory class
30const browserHistory = new BrowserHistory("https://algodaily.com");
31
32// Visiting new URLs
33browserHistory.visit("https://google.com");
34browserHistory.visit("https://facebook.com");
35
36// Navigating back and forth
37console.log(browserHistory.back());  // Should print "https://google.com"
38console.log(browserHistory.back());  // Should print "https://algodaily.com"
39console.log(browserHistory.forward());  // Should print "https://google.com"
40
41// Visiting a new URL from a past page
42browserHistory.visit("https://twitter.com");
43
44console.log(browserHistory.back());  // Should print "https://google.com"
45console.log(browserHistory.forward());  // Should print "https://twitter.com"

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.