@figliolia/data-structures
Version:
Efficient data structures for every day programming
63 lines (62 loc) • 1.25 kB
JavaScript
/**
* Min Max Stack
*
* The base construct for the MinStack and MaxStack utilities
*/
export class MinMaxStack {
storage = [];
occurances = 0;
valueExtractor;
constructor(valueExtractor) {
this.valueExtractor = valueExtractor;
}
/**
* Push
*
* Adds a new value to the stack
*/
push(val) {
this.storage.push(val);
this.setMinMax(val);
}
/**
* Pop
*
* Removes the most recently added value from the stack
*/
pop() {
const val = this.storage.pop();
if (val === undefined) {
return;
}
this.findMinMax(val);
return val;
}
/**
* Peek
*
* Returns the most recently added value from the stack
*/
peek() {
return this.storage[this.storage.length - 1];
}
/**
* Length
*
* Returns the number of items in the stack
*/
get length() {
return this.storage.length;
}
extract(value) {
if (typeof value === "number") {
return value;
}
return this.valueExtractor(value);
}
*[Symbol.iterator]() {
for (const item of this.storage) {
yield item;
}
}
}