Putting It All Together
Here's the full BrowserHistory
class with all its glory:
JAVASCRIPT
1class BrowserHistory {
2 constructor(url) {
3 this.history = [];
4 this.pointer = 0;
5 if (url !== undefined) {
6 this.history.push(url);
7 }
8 }
9
10 visit(url) {
11 this.history.length = this.pointer + 1;
12 this.history.push(url);
13 this.pointer++;
14 }
15
16 back() {
17 this.pointer = Math.max(0, --this.pointer);
18 }
19
20 forward() {
21 this.pointer = Math.min(this.history.length - 1, ++this.pointer);
22 }
23}
And there you have it—a simplified browser history tracker! This class now allows you to maintain a list of visited URLs and navigate through them just like a real browser.