UNPKG

@lf-lang/reactor-ts

Version:

A reactor-oriented programming framework in TypeScript

112 lines 3.18 kB
"use strict"; /** * @file A collection of classes for handling queues. * @author Marten Lohstroh <marten@berkeley.edu> */ Object.defineProperty(exports, "__esModule", { value: true }); exports.PrioritySet = void 0; /** * A deduplicating priority queue that overwrites duplicate entries, * based on a singly-linked list. */ class PrioritySet { /** * The number of elements in the queue. */ count = 0; /** * The first-in-line element in the queue. */ head; /** * Empty the queue. */ empty() { this.head = undefined; this.count = 0; } /** * Return the first-in-line element of the queue, but do not remove it. */ peek() { if (this.head != null) { return this.head; } } /** * Return the first-in-line element of the queue and remove it. */ pop() { if (this.head != null) { const node = this.head; this.head = this.head.next; node.next = undefined; // unhook from linked list this.count--; return node; } } /** * Insert a new element into the queue based on its priority. * If a duplicate entry already exists, abort the insertion. * @param element The element to push onto the queue. */ push(element) { // update linked list if (this.head === undefined) { // create head element.next = undefined; this.head = element; this.count++; } else if (element.updateIfDuplicateOf(this.head)) { // updateIfDuplicateOf returned true, i.e., // it has updated the value of this.head to // equal that of element. } else { // prepend if (element.hasPriorityOver(this.head)) { element.next = this.head; this.head = element; this.count++; return; } // seek let curr = this.head; while (curr != null) { const next = curr.next; if (next != null) { if (element.updateIfDuplicateOf(next)) { // updateIfDuplicateOf returned true, i.e., // it has updated the value of this.head to // equal that of element. return; } else if (element.hasPriorityOver(next)) { break; } else { curr = next; } } else { break; } } if (curr != null) { // insert element.next = curr.next; // undefined if last curr.next = element; this.count++; } } } /** * Return the number of elements in the queue. */ size() { return this.count; } } exports.PrioritySet = PrioritySet; //# sourceMappingURL=queue.js.map