|
| 1 | +/** |
| 2 | + * 1472. Design Browser History |
| 3 | + * https://leetcode.com/problems/design-browser-history/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have a browser of one tab where you start on the homepage and you |
| 7 | + * can visit another url, get back in the history number of steps or move |
| 8 | + * forward in the history number of steps. |
| 9 | + * |
| 10 | + * Implement the BrowserHistory class: |
| 11 | + * |
| 12 | + * - `BrowserHistory(string homepage)` Initializes the object with the |
| 13 | + * homepage of the browser. |
| 14 | + * - `void visit(string url)` Visits url from the current page. It clears |
| 15 | + * up all the forward history. |
| 16 | + * - `string back(int steps)` Move steps back in history. If you can only |
| 17 | + * return x steps in the history and steps > x, you will return only x |
| 18 | + * steps. Return the current url after moving back in history at most steps. |
| 19 | + * - `string forward(int steps)` Move steps forward in history. If you can |
| 20 | + * only forward x steps in the history and steps > x, you will forward only |
| 21 | + * x steps. Return the current url after forwarding in history at most steps. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} homepage |
| 26 | + */ |
| 27 | +var BrowserHistory = function(homepage) { |
| 28 | + this.history = []; |
| 29 | + this.cursor = -1; |
| 30 | + this.visit(homepage); |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * @param {string} url |
| 35 | + * @return {void} |
| 36 | + */ |
| 37 | +BrowserHistory.prototype.visit = function(url) { |
| 38 | + this.history.splice(this.cursor + 1, this.history.length); |
| 39 | + this.history.push(url); |
| 40 | + this.cursor++; |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * @param {number} steps |
| 45 | + * @return {string} |
| 46 | + */ |
| 47 | +BrowserHistory.prototype.back = function(steps) { |
| 48 | + this.cursor = Math.max(0, this.cursor - steps); |
| 49 | + return this.history[this.cursor]; |
| 50 | +}; |
| 51 | + |
| 52 | +/** |
| 53 | + * @param {number} steps |
| 54 | + * @return {string} |
| 55 | + */ |
| 56 | +BrowserHistory.prototype.forward = function(steps) { |
| 57 | + this.cursor = Math.min(this.cursor + steps, this.history.length - 1); |
| 58 | + return this.history[this.cursor]; |
| 59 | +}; |
0 commit comments