One Pager Cheat Sheet
- You can create a simplified version of a browser history tracker that will keep track of the order of visited pages (URLs) and implement logic for visiting the previous, current and following websites.
- The
BrowserHistory
class should include ahistory
array, apointer
property and methods for visiting, going back, and going forward to the previously and next visited website URLs.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
45
console.log(browserHistory.forward()); // Should print "https://twitter.com"
// BrowserHistory class definition
class BrowserHistory {
constructor(url) {
this.history = [];
this.pointer = -1;
if (url !== undefined) {
this.history.push(url);
this.pointer++;
}
}
visit(url) {
this.history = this.history.slice(0, this.pointer + 1);
this.history.push(url);
this.pointer++;
}
back() {
this.pointer = Math.max(0, --this.pointer);
return this.history[this.pointer];
}
forward() {
this.pointer = Math.min(this.history.length - 1, ++this.pointer);
return this.history[this.pointer];
}
}
// Driver code to test the BrowserHistory class
const browserHistory = new BrowserHistory("https://algodaily.com");
// Visiting new URLs
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.