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() {
}
}
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)
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;
}
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++;
}
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;
}
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;
}
To move forward, ensure that a future page exists
forward() {
if (this.index < this.history.length - 1) {
this.index++;
}
return this.current;
}
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;
}
}
That's all folks!
Top comments (0)