|
| 1 | +/** |
| 2 | + * Title: Design Browser History |
| 3 | + * Description: You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 06/04/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {string} homepage |
| 10 | + */ |
| 11 | +var BrowserHistory = function (homepage) { |
| 12 | + this.backHistory = []; |
| 13 | + this.forwardHistory = []; |
| 14 | + this.current = homepage; |
| 15 | +}; |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string} url |
| 19 | + * @return {void} |
| 20 | + */ |
| 21 | +BrowserHistory.prototype.visit = function (url) { |
| 22 | + this.backHistory.push(this.current); |
| 23 | + this.current = url; |
| 24 | + this.forwardHistory = []; |
| 25 | +}; |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number} steps |
| 29 | + * @return {string} |
| 30 | + */ |
| 31 | +BrowserHistory.prototype.back = function (steps) { |
| 32 | + if (!this.backHistory.length) return this.current; |
| 33 | + |
| 34 | + while (steps > 0 && this.backHistory.length) { |
| 35 | + this.forwardHistory.push(this.current); |
| 36 | + this.current = this.backHistory.pop(); |
| 37 | + steps--; |
| 38 | + } |
| 39 | + |
| 40 | + return this.current; |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * @param {number} steps |
| 45 | + * @return {string} |
| 46 | + */ |
| 47 | +BrowserHistory.prototype.forward = function (steps) { |
| 48 | + if (!this.forwardHistory.length) return this.current; |
| 49 | + |
| 50 | + while (steps > 0 && this.forwardHistory.length) { |
| 51 | + this.backHistory.push(this.current); |
| 52 | + this.current = this.forwardHistory.pop(); |
| 53 | + steps--; |
| 54 | + } |
| 55 | + |
| 56 | + return this.current; |
| 57 | +}; |
| 58 | + |
| 59 | +/** |
| 60 | + * Your BrowserHistory object will be instantiated and called as such: |
| 61 | + * var obj = new BrowserHistory(homepage) |
| 62 | + * obj.visit(url) |
| 63 | + * var param_2 = obj.back(steps) |
| 64 | + * var param_3 = obj.forward(steps) |
| 65 | + */ |
0 commit comments