Skip to content

Instantly share code, notes, and snippets.

@nmzaheer
Last active October 20, 2022 18:03
Show Gist options
  • Save nmzaheer/99785c5ec7ce5be132d32adee94d858c to your computer and use it in GitHub Desktop.
Save nmzaheer/99785c5ec7ce5be132d32adee94d858c to your computer and use it in GitHub Desktop.
Testing implementation of HistoryList
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());
@nmzaheer
Copy link
Author

nmzaheer commented Oct 20, 2022

Expected one as output when the first next() method is run. However two is printed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment