Skip to content

Instantly share code, notes, and snippets.

@johnarban
Created June 23, 2026 22:44
Show Gist options
  • Select an option

  • Save johnarban/f57b1dcd8563dda625bb033bfc9e1ea4 to your computer and use it in GitHub Desktop.

Select an option

Save johnarban/f57b1dcd8563dda625bb033bfc9e1ea4 to your computer and use it in GitHub Desktop.
A keyed stack or LRU-like cache. push things on to the stack and as it fills up it pops them off the bottom
/**
* A stacked hashmap of max height.
* The first element is the first removed
*/
class KeyedStack<K, T> {
private _stack: K[] = [];
private _map: Map<K, T> = new Map();
private _maxSize: number;
private _clobber: boolean;
constructor(size: number = Infinity, clobber = false) {
this._maxSize = size;
this._clobber = clobber;
if (clobber) {
console.warn("Allowing clobbering can adversely affect performance");
}
}
/**
* Validate Stack making sure the internal stack and map are tracking each other
*/
validate(sizeOnly = false) {
// validation check size and size of map are the same and have the same keys
if (this._stack.length !== this._map.size) {
console.error(this._stack, this._map);
throw new Error("The map and stack array are different");
}
if (!sizeOnly) { // this is the possible expensive check
const check3 = this._stack.every(k => this._map.has(k));
if (!check3) {
throw new Error("The stack has different keys than the map");
}
}
}
private _removeBottomItem(): null | [K, T | undefined] {
if (this._stack.length === 0) return null;
const bk = this._stack.shift()!; // pop but from the left. not length 0, so it has something
const value = this._map.get(bk); // map.get can handle undefined, value will be undefined
if (!this._map.delete(bk)) { // true if deleted, false if doesn't exist
throw new Error(`${String(bk)} is in stack but not on map`);
}
return [bk, value]; // could be undefined
}
/**
* pop the bottom [key, value] pair off the stack
*/
pop() {
return this._removeBottomItem();
}
/**
* Push on to the keyed stacked
* return true if successfull
* return false if key already existed and clobber is false
*/
push(key: K, value: T): boolean {
const duplicate = this._map.has(key);
if (!this._clobber && duplicate) {
console.debug(`Key '${key}' already exists`);
return false;
}
if (duplicate) { // reorder _stack without making it longer
const idx = this._stack.indexOf(key);
if (idx > -1) {
this._stack.splice(idx,1); // remove 1
this._stack.push(key); // add 1
}
} else {
this._stack.push(key);
}
this._map.set(key, value);
if (this._stack.length > this._maxSize) {
const removed = this._removeBottomItem();
}
return true;
}
has(key: K): boolean {
return this._map.has(key);
}
get(key: K): T | undefined {
return this._map.get(key);
}
toString() {
return this.items.map(v => v.join(' => ')).join(', ');
}
get size(): number {
return this._stack.length;
}
/* ==== Accessor function */
/** get the (key, values) in order */
get items(): [K,T][] {
return this._stack.map(k => [k, this._map.get(k)]) as [K, T][];
}
/** get the values in order */
get values(): T[] {
return this._stack.map(k => this._map.get(k)) as T[];
}
/** get the map in order */
get map() {
return new Map(this.items);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment