Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Created May 2, 2020 22:03
Show Gist options
  • Save n1ru4l/12ec3f621b7b810320a0b605d292da28 to your computer and use it in GitHub Desktop.
Save n1ru4l/12ec3f621b7b810320a0b605d292da28 to your computer and use it in GitHub Desktop.
class Stack<TType extends any> {
#revision = 0;
#revisionOffset = 0;
#items = [] as Array<TType>;
#maximumSize: number;
constructor(maxiumSize = 100) {
if (maxiumSize < 1) {
throw new TypeError("Minimum 'maximumSize' is 1.");
}
this.#maximumSize = maxiumSize;
}
push(item: TType) {
this.#revision = this.#revision + 1;
this.#items.push(item);
const itemAmount = this.#items.length;
if (itemAmount > this.#maximumSize) {
this.#items.shift();
this.#revisionOffset = this.#revisionOffset + 1;
}
return this.#revision;
}
getSince(lastRevision: number) {
const realIndex = lastRevision + 1 - this.#revisionOffset;
if (realIndex < 0) {
return null;
}
return this.#items.slice(realIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment