@figliolia/data-structures
Version:
Efficient data structures for every day programming
66 lines (65 loc) • 1.39 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MinMaxStack = void 0;
/**
* Min Max Stack
*
* The base construct for the MinStack and MaxStack utilities
*/
class MinMaxStack {
constructor(valueExtractor) {
this.storage = [];
this.occurances = 0;
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;
}
}
}
exports.MinMaxStack = MinMaxStack;