Skip to content

Instantly share code, notes, and snippets.

@brandonweis
Created June 27, 2022 15:29
Show Gist options
  • Select an option

  • Save brandonweis/0319af74144fb9d9bbf973eb05fcb95b to your computer and use it in GitHub Desktop.

Select an option

Save brandonweis/0319af74144fb9d9bbf973eb05fcb95b to your computer and use it in GitHub Desktop.
// 实现一个浏览器的前进、后退与前进网址的功能
current -> a
backup -> c, b
class Navigator {
backup = [];
current = [];
forward(): string {
// get from backward stack and push to current stack
const result = this.backup.pop();
if(!result) {
return result
}
current.push(result);
return this.current.length === 0 ? "" : this.current[this.current.length - 1];
}
backward(): string {
// get from current stack and push to backward stack
const result = current.pop();
this.backup.push(result);
return this.current.length === 0 ? "" : this.current[this.current.length - 1];
}
visit(url: string):void {
current.push(url);
}
refresh():void {
}
}
const navigator = new Navigator();
navigator.visit('https://www.google.com'); // current = ['https://www.google.com'], backup = []
navigator.visit('https://www.youtube.com'); // current = ['https://www.google.com', 'https://www.youtube.com'], backup = []
expect(navigator.backward()).toBe('https://www.google.com'); // current = ['https://www.google.com'], backup = ['https://www.youtube.com']
expect(navigator.forward()).toBe('https://www.youtube.com'); // current = ['https://www.google.com', 'https://www.youtube.com'], backup = []
navigator.backward(); // current = ['https://www.google.com'], backup = ['https://www.youtube.com']
navigator.backward(); // current = [], backup = ['https://www.youtube.com', 'https://www.google.com']
navigator.visit('https://www.facebook.com'); // current = ['https://www.facebook.com'], backup = ['https://www.youtube.com', 'https://www.google.com']
expect(navigator.backword()).toBe(''); // current = [], backup = ['https://www.youtube.com', 'https://www.google.com', 'https://www.facebook.com']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment