malwoden
Version:
   
84 lines • 2.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArrayPriorityQueue = void 0;
/**
* ArrayPriorityQueue allows for push/pop based on an attribute
* of the inserted objects. The array based implementation
* underneath has theoretic O(c) insert time, and O(n)
* peek/pop time.
*
* Though this is slower in many cases than the heap based implementation,
* it preserves the order better and can result in more 'normal' paths
* when used with pathfinding.
*/
var ArrayPriorityQueue = /** @class */ (function () {
/**
* @param priorityFunc - A function that takes the a value that
* has previously been inserted, and returns a priority.
*
* A lower score is higher priority.
*
* Ex. (monster) => monster.speed
*/
function ArrayPriorityQueue(priorityFunc) {
this.data = [];
this.priorityFunc = priorityFunc;
}
/**
* Insert data into the queue
* @param data - The data to insert
*/
ArrayPriorityQueue.prototype.insert = function (data) {
var score = this.priorityFunc(data);
this.data.push([score, data]);
};
/**
* Get the item with the lowest priority score,
* removing it from the queue.
* @returns - The lowest priority item
*/
ArrayPriorityQueue.prototype.pop = function () {
if (this.data.length === 0)
return undefined;
var min = Infinity;
var minIndex = -1;
this.data.forEach(function (_a, index) {
var val = _a[0], d = _a[1];
if (val < min) {
min = val;
minIndex = index;
}
});
var popped = this.data.splice(minIndex, 1);
return popped[0][1];
};
/**
* Get the item with the lowest priotity score,
* WITHOUT removing it.
* @returns - The lowest priority item
*/
ArrayPriorityQueue.prototype.peek = function () {
if (this.data.length === 0)
return undefined;
var min = Infinity;
var minIndex = -1;
this.data.forEach(function (_a, index) {
var val = _a[0], d = _a[1];
if (val < min) {
min = val;
minIndex = index;
}
});
return this.data[minIndex][1];
};
/**
* Returns the number of items in the queue.
* @returns - Number of items in the queue.
*/
ArrayPriorityQueue.prototype.size = function () {
return this.data.length;
};
return ArrayPriorityQueue;
}());
exports.ArrayPriorityQueue = ArrayPriorityQueue;
//# sourceMappingURL=priority-queue-array.js.map