Last active
October 18, 2022 21:56
-
-
Save gladchinda/5bb9185152c4c4d962f4679dbd320b6a to your computer and use it in GitHub Desktop.
Configurable array-based queue for JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ArrayQueue = (() => { | |
const __enumerable__ = value => ({ value, enumerable: true }); | |
function ArrayQueue(config) { | |
if (!(this instanceof ArrayQueue)) { | |
return new ArrayQueue(config); | |
} | |
const { equal, fifo, maxsize, reorder } = | |
Object.prototype.toString.call(config) === "[object Object]" | |
? { ...config } | |
: { maxsize: config }; | |
const $queue = []; | |
const $equal = typeof equal === "function" | |
? (a, b) => equal(a, b) === true | |
: (a, b) => a === b; | |
const $maxsize = Math.max(0, Math.min( | |
Number.isInteger(maxsize) && maxsize, | |
ArrayQueue.MAX_SIZE | |
)) || ArrayQueue.MAX_SIZE; | |
const $fifo = fifo !== false; | |
const $reorder = reorder === true; | |
const _index = value => $queue.findIndex(item => $equal(item, value)); | |
const _remove = (...args) => { | |
const index = +(args.length > 0 && _index(args[0])); | |
const removed = (index >= 0 ? $queue.splice(index, 1) : [])[0]; | |
return removed == undefined ? null : removed; | |
}; | |
const iterator = function*() { yield* $queue }; | |
const dequeue = (...args) => $fifo ? _remove() : _remove(...args); | |
const enqueue = value => { | |
if (value != undefined) { | |
if ($reorder) _remove(value); | |
else if (_index(value) >= 0) return; | |
if ($queue.length === $maxsize) throw ArrayQueue.MAX_SIZE_ERROR; | |
$queue.push(value); | |
} | |
}; | |
const peek = () => $queue.length > 0 ? $queue[0] : null; | |
Object.defineProperties(this, { | |
[Symbol.iterator]: __enumerable__(iterator), | |
size: { get: () => $queue.length }, | |
maxsize: __enumerable__($maxsize), | |
dequeue: __enumerable__(dequeue), | |
enqueue: __enumerable__(enqueue), | |
peek: __enumerable__(peek) | |
}); | |
} | |
return Object.defineProperties(ArrayQueue, { | |
MAX_SIZE: __enumerable__(Math.pow(2, 32) - 1), | |
MAX_SIZE_ERROR: __enumerable__(new Error("Cannot exceed maximum queue size.")) | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment