Last active
October 20, 2022 18:03
-
-
Save nmzaheer/99785c5ec7ce5be132d32adee94d858c to your computer and use it in GitHub Desktop.
Testing implementation of HistoryList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HistoryList { | |
private readonly items: string[] = []; | |
private index = -1; | |
constructor(private readonly size = 100) {} | |
push(val: string): void { | |
this.items.push(val); | |
while (this.items.length > this.size) { | |
this.items.shift(); | |
} | |
this.index = -1; | |
} | |
previous(): string { | |
if (this.index === -1) { | |
this.index = this.items.length - 1; | |
return this.items[this.index]; | |
} | |
if (this.hasPrevious) { | |
return this.items[--this.index]; | |
} | |
return this.items[this.index]; | |
} | |
private get hasPrevious(): boolean { | |
return this.index >= 1; | |
} | |
next(): string { | |
if (this.index === this.items.length - 1) { | |
this.index = -1; | |
return ''; | |
} | |
if (this.hasNext) { | |
return this.items[++this.index]; | |
} | |
return ''; | |
} | |
private get hasNext(): boolean { | |
return this.index >= 0 && this.index !== this.items.length - 1; | |
} | |
} | |
var historylist: HistoryList = new HistoryList(10); | |
historylist.push('one'); | |
historylist.push('two'); | |
historylist.push(''); | |
historylist.push('three'); | |
console.log(historylist.next()); | |
console.log(historylist.previous()); | |
console.log(historylist.next()); | |
console.log(historylist.previous()); | |
console.log(historylist.previous()); | |
console.log(historylist.previous()); | |
console.log(historylist.previous()); | |
console.log(historylist.previous()); | |
console.log(historylist.next()); | |
console.log(historylist.next()); | |
console.log(historylist.next()); | |
console.log(historylist.next()); | |
console.log(historylist.next()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected
one
as output when the firstnext()
method is run. Howevertwo
is printed.