-
Notifications
You must be signed in to change notification settings - Fork 1
/
browserHistory.js
53 lines (46 loc) · 1.36 KB
/
browserHistory.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/** To simulate browser history, we need a way to keep track of visited URLs and navigate back and forth.
We can use two stacks to model the back and forward browser functionality.
The main stack (stk1) keeps track of the browsing history where the top of the stack is the current page being viewed.
Another stack (stk2) is used to keep track of the pages that have been gone back from, enabling us to navigate forward.
**/
class BrowserHistory {
/**
* @param {string} url
* if url is set, it means new tab with url
* otherwise, it is empty new tab
*/
constructor(url) {
this.backStack = [];
this.forwardStack = [];
this.backStack.push(url);
}
/**
* @param { string } url
*/
visit(url) {
this.backStack.push(url);
this.forwardStack = [];
}
/**
* @return {string} current url
*/
get current() {
return this.backStack[this.backStack.length-1];
}
// go to previous entry
goBack() {
if(this.backStack.length>1){
let currentEntry = this.backStack.pop();
this.forwardStack.push(currentEntry);
return this.backStack[this.backStack.length-1];
}
}
// go to next visited url
forward() {
if(this.forwardStack.length>1){
let currentEntry = this.forwardStack.pop();
this.backStack.push(currentEntry);
return this.forwardStack[this.forwardStack.length-1];
}
}
}