diff --git a/README.md b/README.md
index 4ec7f89..cca534c 100644
--- a/README.md
+++ b/README.md
@@ -2,13 +2,16 @@
The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use cases such as task queues, breadth-first search (BFS), and similar scenarios.
+This versatile data structure is commonly associated with task prioritization, ensuring tasks are processed in order. It also proves valuable in optimizing sliding-window algorithms, where the oldest item (First In) is evicted based on a specific indicator.
+
## Data-Oriented Design :gear:
This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout and access patterns using arrays, particularly to enhance CPU cache efficiency. Unlike Object-Oriented Programming (OOP), where each object may be allocated in disparate locations on the heap, DOD leverages the sequential allocation of arrays, reducing the likelihood of cache misses.
## Focused API :dart:
-This package provides a queue and nothing more. The absence of linear operations like iteration and splicing reflects a deliberate design choice, as resorting to such methods often indicates that a queue may not have been the most appropriate data structure in the first place.
+This package provides a queue and nothing more. The absence of linear operations like iteration and splicing reflects a deliberate design choice, as resorting to such methods often indicates that a queue may not have been the most appropriate data structure in the first place.
+The sole exception is the `getSnapshot` method, included to support metrics or statistical analysis, particularly in use cases like tracking the K most recent items.
## Table of Contents :bookmark_tabs:
@@ -21,10 +24,10 @@ This package provides a queue and nothing more. The absence of linear operations
## Key Features :sparkles:
-- __Basic Queue API__: Straightforward API, targeting pure use-cases of queues.
+- __Basic Queue API__: Targeting pure use-cases of queues.
- __Efficiency :gear:__: Featuring a Data-Oriented Design with capacity-tuning capability, to reduce or prevent reallocations of the internal cyclic buffer.
- __Comprehensive Documentation :books:__: The class is thoroughly documented, enabling IDEs to provide helpful tooltips that enhance the coding experience.
-- __Tests :test_tube:__: **Fully covered** by comprehensive unit tests, including validations to ensure that internal capacity increases as expected.
+- __Tests :test_tube:__: **Fully covered** by comprehensive unit tests, including **randomized simulations** of real-life scenarios and validations to ensure proper internal capacity scaling.
- **TypeScript** support.
- No external runtime dependencies: Only development dependencies are used.
- ES2020 Compatibility: The `tsconfig` target is set to ES2020, ensuring compatibility with ES2020 environments.
@@ -33,9 +36,10 @@ This package provides a queue and nothing more. The absence of linear operations
The `SlimQueue` class provides the following methods:
-* __push__: Appends the item to the end of the queue as the "Last In" item. As a result, the queue's size increases by one.
-* __pop__: Returns the oldest item currently stored in the queue and removes it. As a result, the queue's size decreases by one.
-* __clear__: Removes all items from the current queue instance, leaving it empty.
+* __push__: Appends an item to the end of the queue (i.e., the Last In), increasing its size by one.
+* __pop__: Removes and returns the oldest (First In) item from the queue, decreasing its size by one.
+* __clear__: Removes all items from the queue, leaving it empty.
+* __getSnapshot__: Returns an array of references to all the currently stored items in the queue, ordered from First-In to Last-In.
If needed, refer to the code documentation for a more comprehensive description.
@@ -47,15 +51,16 @@ The `SlimQueue` class provides the following getter methods to reflect the curre
* __size__: The amount of items currently stored in the queue.
* __isEmpty__: Indicates whether the queue does not contain any item.
+* __firstIn__: Returns a reference to the oldest item currently stored in the queue (the First In item), which will be removed during the next pop operation.
* __capacity__: The length of the internal buffer storing items. If the observed capacity remains significantly larger than the queue's size after the initial warm-up period, it may indicate that the initial capacity was overestimated. Conversely, if the capacity has grown excessively due to buffer reallocations, it may suggest that the initial capacity was underestimated.
* __numberOfCapacityIncrements__: The number of internal buffer reallocations due to insufficient capacity that have occurred during the instance's lifespan. A high number of capacity increments suggests that the initial capacity was underestimated.
-* __firstIn__: The oldest item currently stored in the queue, i.e., the "First In" item, which will be removed during the next pop operation.
To eliminate any ambiguity, all getter methods have **O(1)** time and space complexity.
## Use Case Example: Rate Limiting :man_technologist:
-Consider a component designed for rate-limiting promises using a sliding-window approach. Suppose a window duration of `windowDurationMs` milliseconds, with a maximum of `tasksPerWindow` tasks allowed within each window. The rate limiter will only trigger the execution of a task if fewer than `tasksPerWindow` tasks have started execution within the time window `[now - windowDurationMs, now]`.
+Consider a component designed for rate-limiting promises using a sliding-window approach. Suppose a window duration of `windowDurationMs` milliseconds, with a maximum of `tasksPerWindow` tasks allowed within each window. The rate limiter will only trigger the execution of a task if fewer than `tasksPerWindow` tasks have started execution within the time window `[now - windowDurationMs, now]`.
+
For simplicity, this example focuses on a single method that initiates task execution only if the current window's limit has not been reached. If the limit has been exceeded, an error is thrown.
In this scenario, we employ the `isEmpty`, `firstIn`, and `size` getters, along with the `push` and `pop` methods.
@@ -82,11 +87,8 @@ class RateLimiter {
public async tryExecutingTask(task: RateLimiterTask): Promise {
// Evict out-of-window past execution timestamps.
- const absoluteNow: number = Date.now();
- while (
- !this._ascWindowTimestamps.isEmpty &&
- (absoluteNow - this._ascWindowTimestamps.firstIn) >= this._windowDurationMs
- ) {
+ const now: number = Date.now();
+ while (this._isOutdatedFirstIn(now)) {
this._ascWindowTimestamps.pop();
}
@@ -94,8 +96,18 @@ class RateLimiter {
throw new RateLimiterThrottlingError();
}
- this._ascWindowTimestamps.push(absoluteNow);
- return await task();
+ this._ascWindowTimestamps.push(now);
+ return task();
+ }
+
+ // Eviction indicator.
+ private _isOutdatedFirstIn(now: number): boolean {
+ if (this._ascWindowTimestamps.isEmpty) {
+ return false;
+ }
+
+ const elapsedMsSinceOldestTimestamp = now - this._ascWindowTimestamps.firstIn;
+ return elapsedMsSinceOldestTimestamp >= this._windowDurationMs;
}
}
```
diff --git a/dist/data-oriented-slim-queue.d.ts b/dist/data-oriented-slim-queue.d.ts
index 9688df2..960d443 100644
--- a/dist/data-oriented-slim-queue.d.ts
+++ b/dist/data-oriented-slim-queue.d.ts
@@ -18,24 +18,24 @@ export declare const DEFAULT_SLIM_QUEUE_CAPACITY_INCREMENT_FACTOR = 1.5;
/**
* SlimQueue
*
- * The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use cases
- * like task queues, breadth-first search (BFS), and similar scenarios.
+ * The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use
+ * cases like task queues, breadth-first search (BFS), and similar scenarios.
*
* ### Data-Oriented Design
- * This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout and
- * access patterns using arrays, particularly to enhance CPU cache efficiency. Unlike Object-Oriented Programming
- * (OOP), where each object may be allocated in disparate locations on the heap, DOD leverages the sequential
- * allocation of arrays, reducing the likelihood of cache misses.
+ * This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout
+ * and access patterns using arrays, particularly to enhance CPU cache efficiency.
+ * Unlike Object-Oriented Programming (OOP), where each object may be allocated in disparate locations
+ * on the heap, DOD leverages the sequential allocation of arrays, reducing the likelihood of cache misses.
*
* ### Focused API
- * This package provides a queue and nothing more. The absence of linear operations like iteration and splicing
- * reflects a deliberate design choice, as resorting to such methods often indicates that a queue may not have
- * been the most appropriate data structure in the first place.
+ * This package provides a queue and nothing more. The absence of linear operations like iteration
+ * and splicing reflects a deliberate design choice, as resorting to such methods often indicates that
+ * a queue may not have been the most appropriate data structure in the first place.
*
* ### Terminology
* The 'push' and 'pop' terminology is inspired by std::queue in C++.
- * Unlike more complex data structures, a queue only allows pushing in one direction and popping from the other,
- * making this straightforward terminology appropriate.
+ * Unlike more complex data structures, a queue only allows pushing in one direction and popping from the
+ * other, making this straightforward terminology appropriate.
* The `firstIn` getter provides access to the next item to be removed. This is useful in scenarios where
* items are removed based on a specific condition. For example, in a Rate Limiter that restricts the number
* of requests within a time window, an ascending queue of timestamps might represent request times. To determine
@@ -64,7 +64,7 @@ export declare class SlimQueue {
* will be allocated, and all existing items will be transferred to this new
* buffer. The size of the new buffer will be `oldBufferSize * capacityIncrementFactor`.
* For example, if the initial capacity is 100 and the increment factor is 2,
- * the queue will allocate a new buffer of 200 slots before adding the 101st item.
+ * the queue will allocate a new buffer of 200 slots before adding the 101th item.
*
* ### Considerations
* A small initial capacity may lead to frequent dynamic memory reallocations,
@@ -82,7 +82,7 @@ export declare class SlimQueue {
/**
* size
*
- * @returns The amount of items currently stored in the queue.
+ * @returns The number of items currently stored in the queue.
*/
get size(): number;
/**
@@ -94,11 +94,11 @@ export declare class SlimQueue {
/**
* capacity
*
- * The `capacity` getter is useful for metrics and monitoring. If the observed capacity
- * remains significantly larger than the queue's size after the initial warm-up period,
- * it may indicate that the initial capacity was overestimated. Conversely, if the capacity
- * has grown excessively due to buffer reallocations, it may suggest that the initial
- * capacity was underestimated.
+ * The `capacity` getter is useful for metrics and monitoring.
+ * If the observed capacity remains significantly larger than the queue's size after the
+ * initial warm-up period, it may indicate that the initial capacity was overestimated.
+ * Conversely, if the capacity has grown excessively due to buffer reallocations, it may
+ * suggest that the initial capacity was underestimated.
*
* @returns The length of the internal buffer storing items.
*/
@@ -115,37 +115,62 @@ export declare class SlimQueue {
/**
* firstIn
*
- * @returns The oldest item currently stored in the queue, i.e., the "First In" item,
- * which will be removed during the next pop operation.
+ * Returns a reference to the oldest item currently stored in the queue.
+ *
+ * Commonly used in scenarios like sliding-window algorithms, where items
+ * are conditionally removed based on an out-of-window indicator.
+ *
+ * @returns The "First In" item, i.e., the oldest item in the queue,
+ * which will be removed during the next `pop` operation.
*/
get firstIn(): T;
/**
* push
*
- * This method appends the item to the end of the queue as the "Last In" item.
- * As a result, the queue's size increases by one.
+ * Appends an item to the end of the queue (i.e., the Last In), increasing its size by one.
*
- * @param item The item to be added as the Last In, i.e., the newest item in the queue.
- * It will be removed by the pop method only after all the existing items
+ * @param item The item to add as the newest entry in the queue (i.e., the Last In).
+ * It will be removed by the `pop` method only after all existing items
* have been removed.
*/
push(item: T): void;
/**
* pop
*
- * This method returns the oldest item currently stored in the queue and removes it.
- * As a result, the queue's size decreases by one.
+ * Removes and returns the oldest (First In) item from the queue, decreasing its size by one.
*
- * @returns The oldest item currently stored in the queue, i.e., the "First In" item.
+ * @returns The item that was removed from the queue (the First In item).
*/
pop(): T;
/**
* clear
*
- * This method removes all items from the current queue instance, leaving it empty.
+ * Removes all items from the queue, leaving it empty.
*/
clear(): void;
+ /**
+ * getSnapshot
+ *
+ * Returns an array of references to all the currently stored items in the queue,
+ * ordered from First-In to Last-In.
+ *
+ * This method can be used, for example, to periodically log the K most recent metrics,
+ * such as CPU or memory usage.
+ *
+ * @returns An array of references to the queue's items, ordered from First-In to Last-In.
+ */
+ getSnapshot(): T[];
private _increaseCapacityIfNecessary;
private _calculateExclusiveTailIndex;
private _validateCapacityIncrementFactor;
+ /**
+ * _traverseInOrder
+ *
+ * Facilitates traversing the items in the queue in order, from first-in to last-in.
+ * The method accepts a callback, which is invoked with the current item index in
+ * the internal cyclic buffer.
+ *
+ * @param callback The callback to execute, provided with the current item index.
+ */
+ private _traverseInOrder;
}
diff --git a/dist/data-oriented-slim-queue.js b/dist/data-oriented-slim-queue.js
index b4a45ed..9d64008 100644
--- a/dist/data-oriented-slim-queue.js
+++ b/dist/data-oriented-slim-queue.js
@@ -23,24 +23,24 @@ const MAX_ALLOWED_CAPACITY_INCREMENT_FACTOR = 2;
/**
* SlimQueue
*
- * The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use cases
- * like task queues, breadth-first search (BFS), and similar scenarios.
+ * The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use
+ * cases like task queues, breadth-first search (BFS), and similar scenarios.
*
* ### Data-Oriented Design
- * This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout and
- * access patterns using arrays, particularly to enhance CPU cache efficiency. Unlike Object-Oriented Programming
- * (OOP), where each object may be allocated in disparate locations on the heap, DOD leverages the sequential
- * allocation of arrays, reducing the likelihood of cache misses.
+ * This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout
+ * and access patterns using arrays, particularly to enhance CPU cache efficiency.
+ * Unlike Object-Oriented Programming (OOP), where each object may be allocated in disparate locations
+ * on the heap, DOD leverages the sequential allocation of arrays, reducing the likelihood of cache misses.
*
* ### Focused API
- * This package provides a queue and nothing more. The absence of linear operations like iteration and splicing
- * reflects a deliberate design choice, as resorting to such methods often indicates that a queue may not have
- * been the most appropriate data structure in the first place.
+ * This package provides a queue and nothing more. The absence of linear operations like iteration
+ * and splicing reflects a deliberate design choice, as resorting to such methods often indicates that
+ * a queue may not have been the most appropriate data structure in the first place.
*
* ### Terminology
* The 'push' and 'pop' terminology is inspired by std::queue in C++.
- * Unlike more complex data structures, a queue only allows pushing in one direction and popping from the other,
- * making this straightforward terminology appropriate.
+ * Unlike more complex data structures, a queue only allows pushing in one direction and popping from the
+ * other, making this straightforward terminology appropriate.
* The `firstIn` getter provides access to the next item to be removed. This is useful in scenarios where
* items are removed based on a specific condition. For example, in a Rate Limiter that restricts the number
* of requests within a time window, an ascending queue of timestamps might represent request times. To determine
@@ -64,7 +64,7 @@ class SlimQueue {
* will be allocated, and all existing items will be transferred to this new
* buffer. The size of the new buffer will be `oldBufferSize * capacityIncrementFactor`.
* For example, if the initial capacity is 100 and the increment factor is 2,
- * the queue will allocate a new buffer of 200 slots before adding the 101st item.
+ * the queue will allocate a new buffer of 200 slots before adding the 101th item.
*
* ### Considerations
* A small initial capacity may lead to frequent dynamic memory reallocations,
@@ -83,8 +83,8 @@ class SlimQueue {
this._size = 0;
this._numberOfCapacityIncrements = 0;
if (!isNaturalNumber(initialCapacity)) {
- throw new Error(`Failed to instantiate SlimQueue due to a non-natural number initialCapacity ` +
- `of ${initialCapacity}`);
+ throw new Error(`Failed to instantiate SlimQueue: initialCapacity must be a natural number, ` +
+ `but received ${initialCapacity}`);
}
this._validateCapacityIncrementFactor(capacityIncrementFactor);
this._cyclicBuffer = new Array(initialCapacity).fill(undefined);
@@ -93,7 +93,7 @@ class SlimQueue {
/**
* size
*
- * @returns The amount of items currently stored in the queue.
+ * @returns The number of items currently stored in the queue.
*/
get size() {
return this._size;
@@ -109,11 +109,11 @@ class SlimQueue {
/**
* capacity
*
- * The `capacity` getter is useful for metrics and monitoring. If the observed capacity
- * remains significantly larger than the queue's size after the initial warm-up period,
- * it may indicate that the initial capacity was overestimated. Conversely, if the capacity
- * has grown excessively due to buffer reallocations, it may suggest that the initial
- * capacity was underestimated.
+ * The `capacity` getter is useful for metrics and monitoring.
+ * If the observed capacity remains significantly larger than the queue's size after the
+ * initial warm-up period, it may indicate that the initial capacity was overestimated.
+ * Conversely, if the capacity has grown excessively due to buffer reallocations, it may
+ * suggest that the initial capacity was underestimated.
*
* @returns The length of the internal buffer storing items.
*/
@@ -134,23 +134,27 @@ class SlimQueue {
/**
* firstIn
*
- * @returns The oldest item currently stored in the queue, i.e., the "First In" item,
- * which will be removed during the next pop operation.
+ * Returns a reference to the oldest item currently stored in the queue.
+ *
+ * Commonly used in scenarios like sliding-window algorithms, where items
+ * are conditionally removed based on an out-of-window indicator.
+ *
+ * @returns The "First In" item, i.e., the oldest item in the queue,
+ * which will be removed during the next `pop` operation.
*/
get firstIn() {
if (this._size === 0) {
- throw new Error("The firstIn getter of SlimQueue failed due to empty instance");
+ throw new Error("SlimQueue 'firstIn' getter failed: the queue is empty");
}
return this._cyclicBuffer[this._headIndex];
}
/**
* push
*
- * This method appends the item to the end of the queue as the "Last In" item.
- * As a result, the queue's size increases by one.
+ * Appends an item to the end of the queue (i.e., the Last In), increasing its size by one.
*
- * @param item The item to be added as the Last In, i.e., the newest item in the queue.
- * It will be removed by the pop method only after all the existing items
+ * @param item The item to add as the newest entry in the queue (i.e., the Last In).
+ * It will be removed by the `pop` method only after all existing items
* have been removed.
*/
push(item) {
@@ -162,14 +166,13 @@ class SlimQueue {
/**
* pop
*
- * This method returns the oldest item currently stored in the queue and removes it.
- * As a result, the queue's size decreases by one.
+ * Removes and returns the oldest (First In) item from the queue, decreasing its size by one.
*
- * @returns The oldest item currently stored in the queue, i.e., the "First In" item.
+ * @returns The item that was removed from the queue (the First In item).
*/
pop() {
if (this._size === 0) {
- throw new Error("Cannot pop from an empty SlimQueue");
+ throw new Error("SlimQueue 'pop' operation failed: the queue is empty");
}
const oldestItem = this._cyclicBuffer[this._headIndex];
this._cyclicBuffer[this._headIndex] = undefined; // Help the garbage collector, avoid an unnecessary reference.
@@ -182,7 +185,7 @@ class SlimQueue {
/**
* clear
*
- * This method removes all items from the current queue instance, leaving it empty.
+ * Removes all items from the queue, leaving it empty.
*/
clear() {
while (!this.isEmpty) {
@@ -190,6 +193,25 @@ class SlimQueue {
}
this._headIndex = 0;
}
+ /**
+ * getSnapshot
+ *
+ * Returns an array of references to all the currently stored items in the queue,
+ * ordered from First-In to Last-In.
+ *
+ * This method can be used, for example, to periodically log the K most recent metrics,
+ * such as CPU or memory usage.
+ *
+ * @returns An array of references to the queue's items, ordered from First-In to Last-In.
+ */
+ getSnapshot() {
+ const snapshot = new Array(this._size);
+ let snapshotIndex = 0;
+ this._traverseInOrder((currentBufferIndex) => {
+ snapshot[snapshotIndex++] = this._cyclicBuffer[currentBufferIndex];
+ });
+ return snapshot;
+ }
_increaseCapacityIfNecessary() {
const currCapacity = this._cyclicBuffer.length;
if (this._size < currCapacity) {
@@ -200,14 +222,10 @@ class SlimQueue {
// In the new cyclic buffer we re-order items, such that head is located
// at index 0.
let newBufferLastOccupiedIndex = 0;
- for (let i = this._headIndex; i < this._cyclicBuffer.length; ++i) {
- newCyclicBuffer[newBufferLastOccupiedIndex++] = this._cyclicBuffer[i];
- this._cyclicBuffer[i] = undefined;
- }
- for (let i = 0; i < this._headIndex; ++i) {
- newCyclicBuffer[newBufferLastOccupiedIndex++] = this._cyclicBuffer[i];
- this._cyclicBuffer[i] = undefined;
- }
+ this._traverseInOrder((currentBufferIndex) => {
+ newCyclicBuffer[newBufferLastOccupiedIndex++] = this._cyclicBuffer[currentBufferIndex];
+ this._cyclicBuffer[currentBufferIndex] = undefined;
+ });
this._headIndex = 0;
this._cyclicBuffer = newCyclicBuffer;
++this._numberOfCapacityIncrements;
@@ -220,12 +238,32 @@ class SlimQueue {
}
_validateCapacityIncrementFactor(factor) {
if (factor < MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR) {
- throw new Error(`Failed to instantiate SlimQueue due to a too-small capacityIncrementFactor of ` +
- `${factor}. The minimum allowed is ${MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR}`);
+ throw new Error(`Failed to instantiate SlimQueue: The provided capacityIncrementFactor of ` +
+ `${factor} is too small. The minimum allowed value is ${MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR}`);
}
if (factor > MAX_ALLOWED_CAPACITY_INCREMENT_FACTOR) {
- throw new Error(`Failed to instantiate SlimQueue due to a too-large capacityIncrementFactor of ` +
- `${factor}. The maximum allowed is ${MAX_ALLOWED_CAPACITY_INCREMENT_FACTOR}`);
+ throw new Error(`Failed to instantiate SlimQueue: The provided capacityIncrementFactor of ` +
+ `${factor} is too large. The maximum allowed value is ${MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR}`);
+ }
+ }
+ /**
+ * _traverseInOrder
+ *
+ * Facilitates traversing the items in the queue in order, from first-in to last-in.
+ * The method accepts a callback, which is invoked with the current item index in
+ * the internal cyclic buffer.
+ *
+ * @param callback The callback to execute, provided with the current item index.
+ */
+ _traverseInOrder(callback) {
+ let itemsTraversed = 0;
+ let currentBufferIndex = this._headIndex;
+ while (itemsTraversed < this._size) {
+ callback(currentBufferIndex);
+ ++itemsTraversed;
+ if (++currentBufferIndex === this._cyclicBuffer.length) {
+ currentBufferIndex = 0;
+ }
}
}
}
diff --git a/dist/data-oriented-slim-queue.js.map b/dist/data-oriented-slim-queue.js.map
index db441dd..9802be2 100644
--- a/dist/data-oriented-slim-queue.js.map
+++ b/dist/data-oriented-slim-queue.js.map
@@ -1 +1 @@
-{"version":3,"file":"data-oriented-slim-queue.js","sourceRoot":"","sources":["../src/data-oriented-slim-queue.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEU,QAAA,mCAAmC,GAAG,GAAG,CAAC;AAC1C,QAAA,4CAA4C,GAAG,GAAG,CAAC;AAEhE,MAAM,qCAAqC,GAAG,GAAG,CAAC;AAClD,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,SAAS;IAQlB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACH,YACI,kBAA0B,2CAAmC,EAC7D,0BAAkC,oDAA4C;QAtC1E,eAAU,GAAW,CAAC,CAAC;QACvB,UAAK,GAAW,CAAC,CAAC;QAClB,gCAA2B,GAAW,CAAC,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AK,GAAG,CAAC;AAC3C,CAAC"}
\ No newline at end of file
+{"version":3,"file":"data-oriented-slim-queue.js","sourceRoot":"","sources":["../src/data-oriented-slim-queue.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEU,QAAA,mCAAmC,GAAG,GAAG,CAAC;AAC1C,QAAA,4CAA4C,GAAG,GAAG,CAAC;AAEhE,MAAM,qCAAqC,GAAG,GAAG,CAAC;AAClD,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAIhD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,SAAS;IAQlB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACH,YACI,kBAA0B,2CAAmC,EAC7D,0BAAkC,oDAA4C;QAtC1E,eAAU,GAAW,CAAC,CAAC;QACvB,UAAK,GAAW,CAAC,CAAC;QAClB,gCAA2B,GAAW,CAAC,CAAC;QAsC5C,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,CAAC;YACpC,MAAM,IAAI,KAAK,CACX,6EAA6E;gBAC7E,gBAAgB,eAAe,EAAE,CACpC,CAAC;QACN,CAAC;QAED,IAAI,CAAC,gCAAgC,CAAC,uBAAuB,CAAC,CAAC;QAC/D,IAAI,CAAC,aAAa,GAAG,IAAI,KAAK,CAAgB,eAAe,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC/E,IAAI,CAAC,wBAAwB,GAAG,uBAAuB,CAAC;IAC5D,CAAC;IAED;;;;OAIG;IACH,IAAW,IAAI;QACX,OAAO,IAAI,CAAC,KAAK,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,IAAW,OAAO;QACd,OAAO,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;;;;;;;;;OAUG;IACH,IAAW,QAAQ;QACf,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IACrC,CAAC;IAED;;;;;;;OAOG;IACH,IAAW,0BAA0B;QAC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C,aAAa,CAAC,MAAM;YACrC,OAAO,SAAS,CAAC;QAErB,OAAO,SAAS,GAAI,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IAClD,CAAC;IAEO,gCAAgC,CAAC,MAAc;QACnD,IAAI,MAAM,GAAG,qCAAqC,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CACX,2EAA2E;gBAC3E,GAAG,MAAM,+CAA+C,qCAAqC,EAAE,CAClG,CAAC;QACN,CAAC;QAED,IAAI,MAAM,GAAG,qCAAqC,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CACX,2EAA2E;gBAC3E,GAAG,MAAM,+CAA+C,qCAAqC,EAAE,CAClG,CAAC;QACN,CAAC;IACL,CAAC;IAED;;;;;;;;OAQG;IACK,gBAAgB,CAAC,QAA0B;QAC/C,IAAI,cAAc,GAAG,CAAC,CAAC;QACvB,IAAI,kBAAkB,GAAG,IAAI,CAAC,UAAU,CAAC;QAEzC,OAAO,cAAc,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;YACjC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;YAC7B,EAAE,cAAc,CAAC;YAEjB,IAAI,EAAE,kBAAkB,KAAK,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC;gBACrD,kBAAkB,GAAG,CAAC,CAAC;YAC3B,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AAzQD,8BAyQC;AAED,SAAS,eAAe,CAAC,GAAW;IAChC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAChC,OAAO,OAAO,IAAI,CAAC,IAAI,OAAO,KAAK,GAAG,CAAC;AAC3C,CAAC"}
\ No newline at end of file
diff --git a/dist/data-oriented-slim-queue.test.js b/dist/data-oriented-slim-queue.test.js
index aa2594f..50a383d 100644
--- a/dist/data-oriented-slim-queue.test.js
+++ b/dist/data-oriented-slim-queue.test.js
@@ -23,17 +23,13 @@ function pushAllPopAllTest(initialCapacity, capacityIncrementFactor, itemsCount)
const queue = new data_oriented_slim_queue_1.SlimQueue(initialCapacity, capacityIncrementFactor);
const repetitionsCount = 5; // Amount of push-all & pop-all repetitions.
const firstItemValue = 1;
- const expectedPopOrder = [];
- // Items are 1,2,3,...
- for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
- expectedPopOrder.push(ithItem);
- }
let expectedNumberOfCapacityIncrements = 0;
for (let currRepetition = 0; currRepetition < repetitionsCount; ++currRepetition) {
expect(queue.isEmpty).toBe(true);
expect(queue.size).toBe(0);
expect(() => queue.firstIn).toThrow();
- // Push all items.
+ // Push all items: 1, 2, 3,..., itemsCount (an ascending numeric sequence from
+ // front to back).
for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
const oldCapacity = queue.capacity;
const shouldTriggerCapacityIncrement = queue.size === queue.capacity;
@@ -51,13 +47,18 @@ function pushAllPopAllTest(initialCapacity, capacityIncrementFactor, itemsCount)
expect(queue.size).toBe(ithItem);
expect(queue.firstIn).toBe(firstItemValue);
}
+ const snapshot = queue.getSnapshot();
+ expect(snapshot.length).toBe(itemsCount);
+ for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
+ expect(snapshot[ithItem - 1]).toBe(ithItem);
+ }
// Pop all items.
- const capacityBeforeRemovingItems = queue.capacity; // Does not change following pop operations.
+ const capacityBeforeRemoval = queue.capacity; // The capacity remains unchanged by pop operations.
for (let ithRemovedItem = 1; ithRemovedItem <= itemsCount; ++ithRemovedItem) {
const removedItem = queue.pop();
expect(removedItem).toBe(ithRemovedItem);
expect(queue.size).toBe(itemsCount - ithRemovedItem);
- expect(queue.capacity).toBe(capacityBeforeRemovingItems);
+ expect(queue.capacity).toBe(capacityBeforeRemoval);
expect(queue.numberOfCapacityIncrements).toEqual(expectedNumberOfCapacityIncrements);
if (ithRemovedItem === itemsCount) {
// The last removed item.
@@ -73,15 +74,17 @@ function pushAllPopAllTest(initialCapacity, capacityIncrementFactor, itemsCount)
}
describe('SlimQueue tests', () => {
describe('Happy path tests', () => {
- test('push all items, then pop all items, expecting no buffer reallocation due to sufficient initialCapacity', async () => {
+ test('push all items, then pop all items, expecting no buffer reallocation ' +
+ 'due to sufficient initial capacity', async () => {
const itemsCount = 116;
const initialCapacity = itemsCount; // No buffer reallocations are expected.
const capacityIncrementFactor = 1.5;
pushAllPopAllTest(initialCapacity, capacityIncrementFactor, itemsCount);
});
- test('push all items, then pop all items, expecting buffer reallocation to occur due to insufficient initialCapacity', async () => {
+ test('push all items, then pop all items, expecting buffer reallocations to occur ' +
+ 'due to insufficient initialCapacity', async () => {
// This test ensures validity following multiple internal buffer reallocations.
- const itemsCount = 412;
+ const itemsCount = 803;
const initialCapacity = 1; // Small initial capacity, to trigger many buffer reallocations.
const capacityIncrementFactor = 1.1; // Relatively small factor, to trigger multiple buffer re-allocations.
pushAllPopAllTest(initialCapacity, capacityIncrementFactor, itemsCount);
@@ -90,83 +93,81 @@ describe('SlimQueue tests', () => {
const repetitionsCount = 5;
const itemsCount = 48;
const queue = new data_oriented_slim_queue_1.SlimQueue();
+ const createItem = (ithItem) => `ITEM_PREFIX_${ithItem}`;
+ const firstItem = createItem(1);
for (let currRepetition = 0; currRepetition < repetitionsCount; ++currRepetition) {
for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
- queue.push(`ITEM_PREFIX_${ithItem}`);
+ const currItem = createItem(ithItem);
+ queue.push(currItem);
}
expect(queue.size).toBe(itemsCount);
expect(queue.isEmpty).toBe(false);
- expect(queue.firstIn).toBe("ITEM_PREFIX_1");
+ expect(queue.firstIn).toBe(firstItem);
queue.clear();
expect(queue.size).toBe(0);
expect(queue.isEmpty).toBe(true);
}
});
- test('push a random number of items, then pop a random number of items, and repeat the process', async () => {
- const mainLoopRepetitions = 51; // Sufficiently big to observe statistical errors (such should not exist).
+ test('push a random number of items, then pop a random number of items, ' +
+ 'perform validations including snapshot validity, and repeat the process', async () => {
+ const numberOfMainLoopRepetitions = 65; // Sufficiently big to observe statistical errors (such should not exist).
const maxRepetitionsForOperationBatch = 76;
- const expectedInternalState = []; // Left to Right -> First In to Last In.
- let nextItemValue = -1451;
+ let nextItemValue = -1403;
+ let expectedFirstIn = nextItemValue;
let expectedSize = 0;
- let expectedNumberOfCapacityIncrements = 0;
- let expectedCapacity = data_oriented_slim_queue_1.DEFAULT_SLIM_QUEUE_INITIAL_CAPACITY;
- const queue = new data_oriented_slim_queue_1.SlimQueue(); // Default params (initial capacity, capacity increment factor.)
- const validatePush = () => {
- if (queue.size === queue.capacity) {
- // A buffer re-allocation is expected to be triggered.
- ++expectedNumberOfCapacityIncrements;
- expectedCapacity = getNewCapacity(expectedCapacity, data_oriented_slim_queue_1.DEFAULT_SLIM_QUEUE_CAPACITY_INCREMENT_FACTOR);
- }
- queue.push(nextItemValue);
- expectedInternalState.push(nextItemValue);
- ++nextItemValue;
+ // The items invariant ensures that items are ordered in an ascending numeric sequence:
+ // -k, -k+1, ..., 0, 1, 2, ..., m-1, m, from front to back (first-in to last-in).
+ const queue = new data_oriented_slim_queue_1.SlimQueue(); // Default params (initial capacity, capacity increment factor).
+ const pushAndValidate = () => {
+ queue.push(nextItemValue++);
++expectedSize;
expect(queue.size).toBe(expectedSize);
- expect(queue.size).toBe(expectedInternalState.length);
expect(queue.isEmpty).toBe(false);
- expect(queue.firstIn).toBe(expectedInternalState[0]);
- expect(queue.capacity).toBe(expectedCapacity);
- expect(queue.numberOfCapacityIncrements).toBe(expectedNumberOfCapacityIncrements);
+ expect(queue.firstIn).toBe(expectedFirstIn);
};
- const validatePopFromNonEmptyQueue = () => {
- const expectedRemovedItem = expectedInternalState[0];
+ const popAndValidate = () => {
+ if (queue.isEmpty) {
+ expect(() => queue.pop()).toThrow();
+ return;
+ }
const removedItem = queue.pop();
- expect(removedItem).toBe(expectedRemovedItem);
- expectedInternalState.shift(); // Inefficient O(n), yet sufficient for testing purposes.
+ expect(removedItem).toBe(expectedFirstIn++);
--expectedSize;
expect(queue.size).toBe(expectedSize);
- expect(queue.size).toBe(expectedInternalState.length);
- expect(queue.capacity).toBe(expectedCapacity);
- expect(queue.numberOfCapacityIncrements).toBe(expectedNumberOfCapacityIncrements);
expect(queue.isEmpty).toBe(expectedSize === 0);
if (!queue.isEmpty) {
- expect(queue.firstIn).toBe(expectedInternalState[0]);
+ expect(queue.firstIn).toBe(expectedFirstIn);
+ }
+ };
+ const validateSnapshot = () => {
+ const snapshot = queue.getSnapshot();
+ expect(snapshot.length).toBe(queue.size);
+ if (queue.isEmpty) {
+ return;
+ }
+ let expectedCurrentItem = expectedFirstIn;
+ for (const currentItem of snapshot) {
+ expect(currentItem).toBe(expectedCurrentItem++);
}
};
- let remainedMainLoopIterations = mainLoopRepetitions;
+ let remainedMainLoopIterations = numberOfMainLoopRepetitions;
do {
const pushCount = Math.ceil(Math.random() * maxRepetitionsForOperationBatch);
const popCount = Math.ceil(Math.random() * maxRepetitionsForOperationBatch);
for (let currPush = 1; currPush <= pushCount; ++currPush) {
- validatePush();
+ pushAndValidate();
}
+ validateSnapshot();
for (let currPop = 1; currPop <= popCount; ++currPop) {
- if (expectedSize === 0) {
- expect(queue.isEmpty).toBe(true);
- expect(queue.size).toBe(0);
- expect(queue.capacity).toBe(expectedCapacity);
- expect(queue.numberOfCapacityIncrements).toBe(expectedNumberOfCapacityIncrements);
- expect(() => queue.firstIn).toThrow();
- expect(expectedInternalState.length).toBe(0);
- continue;
- }
- // Non empty queue.
- validatePopFromNonEmptyQueue();
+ popAndValidate();
}
+ validateSnapshot();
} while (--remainedMainLoopIterations > 0);
+ // Digest: clean the queue.
while (expectedSize > 0) {
- validatePopFromNonEmptyQueue();
+ popAndValidate();
}
+ validateSnapshot();
});
});
describe('Negative path tests', () => {
@@ -190,7 +191,7 @@ describe('SlimQueue tests', () => {
expect(() => new data_oriented_slim_queue_1.SlimQueue(validInitialCapacity, factor)).toThrow();
}
});
- test('should throw when triggering the firstIn getter on an empty instance', () => {
+ test('should throw an error when accessing the firstIn getter on an empty instance', () => {
const queue = new data_oriented_slim_queue_1.SlimQueue();
expect(() => queue.firstIn).toThrow();
});
diff --git a/dist/data-oriented-slim-queue.test.js.map b/dist/data-oriented-slim-queue.test.js.map
index 132acce..71424b8 100644
--- a/dist/data-oriented-slim-queue.test.js.map
+++ b/dist/data-oriented-slim-queue.test.js.map
@@ -1 +1 @@
-{"version":3,"file":"data-oriented-slim-queue.test.js","sourceRoot":"","sources":["../src/data-oriented-slim-queue.test.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAEH,yEAA0I;AAE1I,SAAS,cAAc,CAAC,WAAmB,EAAE,eAAuB;IAClE,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,iBAAiB,CACxB,eAAuB,EACvB,uBAA+B,EAC/B,UAAkB;IAElB,MAAM,KAAK,GAAG,IAAI,oCAAS,CAAS,eAAe,EAAE,uBAAuB,CAAC,CAAC;IAE9E,MAAM,gBAAgB,GAAG,CAAC,CAAC,CAAC,4CAA4C;IACxE,MAAM,cAAc,GAAG,CAAC,CAAC;IACzB,MAAM,gBAAgB,GAAG,EAAE,CAAC;IAE5B,sBAAsB;IACtB,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,UAAU,EAAE,EAAE,OAAO,EAAE,CAAC;QACvD,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;IAED,IAAI,kCAAkC,GAAG,CAAC,CAAC;IAC3C,KAAK,IAAI,cAAc,GAAG,CAAC,EAAE,cAAc,GAAG,gBAAgB,EAAE,EAAE,cAAc,EAAE,CAAC;QACjF,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,EAA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L,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
\ No newline at end of file
+{"version":3,"file":"data-oriented-slim-queue.test.js","sourceRoot":"","sources":["../src/data-oriented-slim-queue.test.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAEH,yEAAuD;AAEvD,SAAS,cAAc,CAAC,WAAmB,EAAE,eAAuB;IAClE,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,iBAAiB,CACxB,eAAuB,EACvB,uBAA+B,EAC/B,UAAkB;IAElB,MAAM,KAAK,GAAG,IAAI,oCAAS,CAAS,eAAe,EAAE,uBAAuB,CAAC,CAAC;IAE9E,MAAM,gBAAgB,GAAG,CAAC,CAAC,CAAC,4CAA4C;IACxE,MAAM,cAAc,GAAG,CAAC,CAAC;IAEzB,IAAI,kCAAkC,GAAG,CAAC,CAAC;IAC3C,KAAK,IAAI,cAAc,GAAG,CAAC,EAAE,cAAc,GAAG,gBAAgB,EAAE,EAAE,cAAc,EAAE,CAAC;QACjF,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;QAEtC,8EAA8E;QAC9E,kBAAkB;QAClB,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,UAAU,EAAE,EAAE,OAAO,EAAE,CAAC;YACvD,MAAM,WAAW,GAAG,KAAK,CAAC,QAAQ,CAAC;YACnC,MAAM,8BAA8B,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,QAAQ,CAAC;YACrE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAEpB,IAAI,8BAA8B,E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CAAC,wEAAwE,EAAE,GAAG,EAAE;YAClF,MAAM,oBAAoB,GAAG,GAAG,CAAC;YACjC,MAAM,qBAAqB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;YACrE,KAAK,MAAM,MAAM,IAAI,qBAAqB,EAAE,CAAC;gBAC3C,MAAM,CAAC,GAAG,EAAE,CAAC,IAAI,oCAAS,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;YACtE,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,8EAA8E,EAAE,GAAG,EAAE;YACxF,MAAM,KAAK,GAAG,IAAI,oCAAS,EAAE,CAAC;YAC9B,MAAM,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 4f810d5..100f2cf 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "data-oriented-slim-queue",
- "version": "1.0.2",
+ "version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "data-oriented-slim-queue",
- "version": "1.0.2",
+ "version": "1.1.0",
"license": "Apache-2.0",
"devDependencies": {
"@types/jest": "^29.5.12",
diff --git a/package.json b/package.json
index ded7a2b..e3cefff 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "data-oriented-slim-queue",
- "version": "1.0.2",
- "description": "A slim and efficient in-memory queue with a basic API for Node.js projects. The implementation employs Data-Oriented Design using a cyclic buffer, optimizing memory layout through sequential item allocation.",
+ "version": "1.1.0",
+ "description": "A slim and efficient in-memory queue for Node.js projects. The implementation employs Data-Oriented Design using a cyclic buffer, optimizing memory layout through sequential item allocation.",
"repository": {
"type": "git",
"url": "git+https://github.com/ori88c/data-oriented-slim-queue.git"
@@ -29,6 +29,8 @@
"cyclic-buffer",
"circular-buffer",
"data-structure",
+ "sequential",
+ "pre-allocated",
"nodejs",
"typescript",
"ts",
diff --git a/src/data-oriented-slim-queue.test.ts b/src/data-oriented-slim-queue.test.ts
index 6fc4e01..1634d38 100644
--- a/src/data-oriented-slim-queue.test.ts
+++ b/src/data-oriented-slim-queue.test.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DEFAULT_SLIM_QUEUE_CAPACITY_INCREMENT_FACTOR, DEFAULT_SLIM_QUEUE_INITIAL_CAPACITY, SlimQueue } from './data-oriented-slim-queue';
+import { SlimQueue } from './data-oriented-slim-queue';
function getNewCapacity(oldCapacity: number, incrementFactor: number): number {
return Math.ceil(oldCapacity * incrementFactor);
@@ -29,12 +29,6 @@ function pushAllPopAllTest(
const repetitionsCount = 5; // Amount of push-all & pop-all repetitions.
const firstItemValue = 1;
- const expectedPopOrder = [];
-
- // Items are 1,2,3,...
- for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
- expectedPopOrder.push(ithItem);
- }
let expectedNumberOfCapacityIncrements = 0;
for (let currRepetition = 0; currRepetition < repetitionsCount; ++currRepetition) {
@@ -42,7 +36,8 @@ function pushAllPopAllTest(
expect(queue.size).toBe(0);
expect(() => queue.firstIn).toThrow();
- // Push all items.
+ // Push all items: 1, 2, 3,..., itemsCount (an ascending numeric sequence from
+ // front to back).
for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
const oldCapacity = queue.capacity;
const shouldTriggerCapacityIncrement = queue.size === queue.capacity;
@@ -62,13 +57,19 @@ function pushAllPopAllTest(
expect(queue.firstIn).toBe(firstItemValue);
}
+ const snapshot = queue.getSnapshot();
+ expect(snapshot.length).toBe(itemsCount);
+ for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
+ expect(snapshot[ithItem - 1]).toBe(ithItem);
+ }
+
// Pop all items.
- const capacityBeforeRemovingItems = queue.capacity; // Does not change following pop operations.
+ const capacityBeforeRemoval = queue.capacity; // The capacity remains unchanged by pop operations.
for (let ithRemovedItem = 1; ithRemovedItem <= itemsCount; ++ithRemovedItem) {
const removedItem = queue.pop();
expect(removedItem).toBe(ithRemovedItem)
expect(queue.size).toBe(itemsCount - ithRemovedItem);
- expect(queue.capacity).toBe(capacityBeforeRemovingItems);
+ expect(queue.capacity).toBe(capacityBeforeRemoval);
expect(queue.numberOfCapacityIncrements).toEqual(expectedNumberOfCapacityIncrements);
if (ithRemovedItem === itemsCount) {
@@ -85,7 +86,9 @@ function pushAllPopAllTest(
describe('SlimQueue tests', () => {
describe('Happy path tests', () => {
- test('push all items, then pop all items, expecting no buffer reallocation due to sufficient initialCapacity', async () => {
+ test(
+ 'push all items, then pop all items, expecting no buffer reallocation ' +
+ 'due to sufficient initial capacity', async () => {
const itemsCount = 116;
const initialCapacity = itemsCount; // No buffer reallocations are expected.
const capacityIncrementFactor = 1.5;
@@ -93,9 +96,11 @@ describe('SlimQueue tests', () => {
pushAllPopAllTest(initialCapacity, capacityIncrementFactor, itemsCount);
});
- test('push all items, then pop all items, expecting buffer reallocation to occur due to insufficient initialCapacity', async () => {
+ test(
+ 'push all items, then pop all items, expecting buffer reallocations to occur ' +
+ 'due to insufficient initialCapacity', async () => {
// This test ensures validity following multiple internal buffer reallocations.
- const itemsCount = 412;
+ const itemsCount = 803;
const initialCapacity = 1; // Small initial capacity, to trigger many buffer reallocations.
const capacityIncrementFactor = 1.1; // Relatively small factor, to trigger multiple buffer re-allocations.
@@ -107,96 +112,98 @@ describe('SlimQueue tests', () => {
const itemsCount = 48;
const queue = new SlimQueue();
+ const createItem = (ithItem: number) => `ITEM_PREFIX_${ithItem}`;
+ const firstItem = createItem(1);
for (let currRepetition = 0; currRepetition < repetitionsCount; ++currRepetition) {
for (let ithItem = 1; ithItem <= itemsCount; ++ithItem) {
- queue.push(`ITEM_PREFIX_${ithItem}`);
+ const currItem = createItem(ithItem);
+ queue.push(currItem);
}
expect(queue.size).toBe(itemsCount);
expect(queue.isEmpty).toBe(false);
- expect(queue.firstIn).toBe("ITEM_PREFIX_1");
+ expect(queue.firstIn).toBe(firstItem);
queue.clear();
expect(queue.size).toBe(0);
expect(queue.isEmpty).toBe(true);
}
});
- test('push a random number of items, then pop a random number of items, and repeat the process', async () => {
- const mainLoopRepetitions = 51; // Sufficiently big to observe statistical errors (such should not exist).
+ test(
+ 'push a random number of items, then pop a random number of items, ' +
+ 'perform validations including snapshot validity, and repeat the process', async () => {
+ const numberOfMainLoopRepetitions = 65; // Sufficiently big to observe statistical errors (such should not exist).
const maxRepetitionsForOperationBatch = 76;
- const expectedInternalState: number[] = []; // Left to Right -> First In to Last In.
- let nextItemValue = -1451;
+ let nextItemValue = -1403;
+ let expectedFirstIn = nextItemValue;
let expectedSize = 0;
- let expectedNumberOfCapacityIncrements = 0;
- let expectedCapacity = DEFAULT_SLIM_QUEUE_INITIAL_CAPACITY;
-
- const queue = new SlimQueue(); // Default params (initial capacity, capacity increment factor.)
- const validatePush = () => {
- if (queue.size === queue.capacity) {
- // A buffer re-allocation is expected to be triggered.
- ++expectedNumberOfCapacityIncrements;
- expectedCapacity = getNewCapacity(expectedCapacity, DEFAULT_SLIM_QUEUE_CAPACITY_INCREMENT_FACTOR);
- }
+ // The items invariant ensures that items are ordered in an ascending numeric sequence:
+ // -k, -k+1, ..., 0, 1, 2, ..., m-1, m, from front to back (first-in to last-in).
+ const queue = new SlimQueue(); // Default params (initial capacity, capacity increment factor).
- queue.push(nextItemValue);
- expectedInternalState.push(nextItemValue);
- ++nextItemValue;
+ const pushAndValidate = (): void => {
+ queue.push(nextItemValue++);
++expectedSize;
expect(queue.size).toBe(expectedSize);
- expect(queue.size).toBe(expectedInternalState.length);
expect(queue.isEmpty).toBe(false);
- expect(queue.firstIn).toBe(expectedInternalState[0]);
- expect(queue.capacity).toBe(expectedCapacity);
- expect(queue.numberOfCapacityIncrements).toBe(expectedNumberOfCapacityIncrements);
+ expect(queue.firstIn).toBe(expectedFirstIn);
};
- const validatePopFromNonEmptyQueue = () => {
- const expectedRemovedItem = expectedInternalState[0];
+ const popAndValidate = (): void => {
+ if (queue.isEmpty) {
+ expect(() => queue.pop()).toThrow();
+ return;
+ }
+
const removedItem = queue.pop();
- expect(removedItem).toBe(expectedRemovedItem);
+ expect(removedItem).toBe(expectedFirstIn++);
- expectedInternalState.shift(); // Inefficient O(n), yet sufficient for testing purposes.
--expectedSize;
expect(queue.size).toBe(expectedSize);
- expect(queue.size).toBe(expectedInternalState.length);
- expect(queue.capacity).toBe(expectedCapacity);
- expect(queue.numberOfCapacityIncrements).toBe(expectedNumberOfCapacityIncrements);
expect(queue.isEmpty).toBe(expectedSize === 0);
if (!queue.isEmpty) {
- expect(queue.firstIn).toBe(expectedInternalState[0]);
+ expect(queue.firstIn).toBe(expectedFirstIn);
+ }
+ };
+
+ const validateSnapshot = (): void => {
+ const snapshot = queue.getSnapshot();
+ expect(snapshot.length).toBe(queue.size);
+ if (queue.isEmpty) {
+ return;
+ }
+
+ let expectedCurrentItem = expectedFirstIn;
+ for (const currentItem of snapshot) {
+ expect(currentItem).toBe(expectedCurrentItem++);
}
};
- let remainedMainLoopIterations = mainLoopRepetitions;
+ let remainedMainLoopIterations = numberOfMainLoopRepetitions;
do {
const pushCount = Math.ceil(Math.random() * maxRepetitionsForOperationBatch);
const popCount = Math.ceil(Math.random() * maxRepetitionsForOperationBatch);
for (let currPush = 1; currPush <= pushCount; ++currPush) {
- validatePush();
+ pushAndValidate();
}
+ validateSnapshot();
+
for (let currPop = 1; currPop <= popCount; ++currPop) {
- if (expectedSize === 0) {
- expect(queue.isEmpty).toBe(true);
- expect(queue.size).toBe(0);
- expect(queue.capacity).toBe(expectedCapacity);
- expect(queue.numberOfCapacityIncrements).toBe(expectedNumberOfCapacityIncrements);
- expect(() => queue.firstIn).toThrow();
- expect(expectedInternalState.length).toBe(0);
- continue;
- }
-
- // Non empty queue.
- validatePopFromNonEmptyQueue();
+ popAndValidate();
}
+
+ validateSnapshot();
} while (--remainedMainLoopIterations > 0);
+ // Digest: clean the queue.
while (expectedSize > 0) {
- validatePopFromNonEmptyQueue();
+ popAndValidate();
}
+ validateSnapshot();
});
});
@@ -224,7 +231,7 @@ describe('SlimQueue tests', () => {
}
});
- test('should throw when triggering the firstIn getter on an empty instance', () => {
+ test('should throw an error when accessing the firstIn getter on an empty instance', () => {
const queue = new SlimQueue();
expect(() => queue.firstIn).toThrow();
});
diff --git a/src/data-oriented-slim-queue.ts b/src/data-oriented-slim-queue.ts
index a773552..8241e77 100644
--- a/src/data-oriented-slim-queue.ts
+++ b/src/data-oriented-slim-queue.ts
@@ -20,27 +20,29 @@ export const DEFAULT_SLIM_QUEUE_CAPACITY_INCREMENT_FACTOR = 1.5;
const MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR = 1.1;
const MAX_ALLOWED_CAPACITY_INCREMENT_FACTOR = 2;
+type TraverseCallback = (currentIndex: number) => void;
+
/**
* SlimQueue
*
- * The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use cases
- * like task queues, breadth-first search (BFS), and similar scenarios.
+ * The `SlimQueue` class implements an in-memory queue with a basic API, targeting pure FIFO use
+ * cases like task queues, breadth-first search (BFS), and similar scenarios.
*
* ### Data-Oriented Design
- * This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout and
- * access patterns using arrays, particularly to enhance CPU cache efficiency. Unlike Object-Oriented Programming
- * (OOP), where each object may be allocated in disparate locations on the heap, DOD leverages the sequential
- * allocation of arrays, reducing the likelihood of cache misses.
+ * This implementation follows the principles of Data-Oriented Design (DOD), optimizing memory layout
+ * and access patterns using arrays, particularly to enhance CPU cache efficiency.
+ * Unlike Object-Oriented Programming (OOP), where each object may be allocated in disparate locations
+ * on the heap, DOD leverages the sequential allocation of arrays, reducing the likelihood of cache misses.
*
* ### Focused API
- * This package provides a queue and nothing more. The absence of linear operations like iteration and splicing
- * reflects a deliberate design choice, as resorting to such methods often indicates that a queue may not have
- * been the most appropriate data structure in the first place.
+ * This package provides a queue and nothing more. The absence of linear operations like iteration
+ * and splicing reflects a deliberate design choice, as resorting to such methods often indicates that
+ * a queue may not have been the most appropriate data structure in the first place.
*
* ### Terminology
* The 'push' and 'pop' terminology is inspired by std::queue in C++.
- * Unlike more complex data structures, a queue only allows pushing in one direction and popping from the other,
- * making this straightforward terminology appropriate.
+ * Unlike more complex data structures, a queue only allows pushing in one direction and popping from the
+ * other, making this straightforward terminology appropriate.
* The `firstIn` getter provides access to the next item to be removed. This is useful in scenarios where
* items are removed based on a specific condition. For example, in a Rate Limiter that restricts the number
* of requests within a time window, an ascending queue of timestamps might represent request times. To determine
@@ -71,7 +73,7 @@ export class SlimQueue {
* will be allocated, and all existing items will be transferred to this new
* buffer. The size of the new buffer will be `oldBufferSize * capacityIncrementFactor`.
* For example, if the initial capacity is 100 and the increment factor is 2,
- * the queue will allocate a new buffer of 200 slots before adding the 101st item.
+ * the queue will allocate a new buffer of 200 slots before adding the 101th item.
*
* ### Considerations
* A small initial capacity may lead to frequent dynamic memory reallocations,
@@ -91,8 +93,8 @@ export class SlimQueue {
) {
if (!isNaturalNumber(initialCapacity)) {
throw new Error(
- `Failed to instantiate SlimQueue due to a non-natural number initialCapacity ` +
- `of ${initialCapacity}`
+ `Failed to instantiate SlimQueue: initialCapacity must be a natural number, ` +
+ `but received ${initialCapacity}`
);
}
@@ -104,7 +106,7 @@ export class SlimQueue {
/**
* size
*
- * @returns The amount of items currently stored in the queue.
+ * @returns The number of items currently stored in the queue.
*/
public get size(): number {
return this._size;
@@ -122,11 +124,11 @@ export class SlimQueue {
/**
* capacity
*
- * The `capacity` getter is useful for metrics and monitoring. If the observed capacity
- * remains significantly larger than the queue's size after the initial warm-up period,
- * it may indicate that the initial capacity was overestimated. Conversely, if the capacity
- * has grown excessively due to buffer reallocations, it may suggest that the initial
- * capacity was underestimated.
+ * The `capacity` getter is useful for metrics and monitoring.
+ * If the observed capacity remains significantly larger than the queue's size after the
+ * initial warm-up period, it may indicate that the initial capacity was overestimated.
+ * Conversely, if the capacity has grown excessively due to buffer reallocations, it may
+ * suggest that the initial capacity was underestimated.
*
* @returns The length of the internal buffer storing items.
*/
@@ -149,12 +151,17 @@ export class SlimQueue {
/**
* firstIn
*
- * @returns The oldest item currently stored in the queue, i.e., the "First In" item,
- * which will be removed during the next pop operation.
+ * Returns a reference to the oldest item currently stored in the queue.
+ *
+ * Commonly used in scenarios like sliding-window algorithms, where items
+ * are conditionally removed based on an out-of-window indicator.
+ *
+ * @returns The "First In" item, i.e., the oldest item in the queue,
+ * which will be removed during the next `pop` operation.
*/
public get firstIn(): T {
if (this._size === 0) {
- throw new Error("The firstIn getter of SlimQueue failed due to empty instance");
+ throw new Error("SlimQueue 'firstIn' getter failed: the queue is empty");
}
return this._cyclicBuffer[this._headIndex];
@@ -163,11 +170,10 @@ export class SlimQueue {
/**
* push
*
- * This method appends the item to the end of the queue as the "Last In" item.
- * As a result, the queue's size increases by one.
+ * Appends an item to the end of the queue (i.e., the Last In), increasing its size by one.
*
- * @param item The item to be added as the Last In, i.e., the newest item in the queue.
- * It will be removed by the pop method only after all the existing items
+ * @param item The item to add as the newest entry in the queue (i.e., the Last In).
+ * It will be removed by the `pop` method only after all existing items
* have been removed.
*/
public push(item: T): void {
@@ -181,14 +187,13 @@ export class SlimQueue {
/**
* pop
*
- * This method returns the oldest item currently stored in the queue and removes it.
- * As a result, the queue's size decreases by one.
+ * Removes and returns the oldest (First In) item from the queue, decreasing its size by one.
*
- * @returns The oldest item currently stored in the queue, i.e., the "First In" item.
+ * @returns The item that was removed from the queue (the First In item).
*/
public pop(): T {
if (this._size === 0) {
- throw new Error("Cannot pop from an empty SlimQueue");
+ throw new Error("SlimQueue 'pop' operation failed: the queue is empty");
}
const oldestItem = this._cyclicBuffer[this._headIndex];
@@ -205,7 +210,7 @@ export class SlimQueue {
/**
* clear
*
- * This method removes all items from the current queue instance, leaving it empty.
+ * Removes all items from the queue, leaving it empty.
*/
public clear(): void {
while (!this.isEmpty) {
@@ -214,7 +219,31 @@ export class SlimQueue {
this._headIndex = 0;
}
-
+
+ /**
+ * getSnapshot
+ *
+ * Returns an array of references to all the currently stored items in the queue,
+ * ordered from First-In to Last-In.
+ *
+ * This method can be used, for example, to periodically log the K most recent metrics,
+ * such as CPU or memory usage.
+ *
+ * @returns An array of references to the queue's items, ordered from First-In to Last-In.
+ */
+ public getSnapshot(): T[] {
+ const snapshot = new Array(this._size);
+
+ let snapshotIndex = 0;
+ this._traverseInOrder(
+ (currentBufferIndex: number) => {
+ snapshot[snapshotIndex++] = this._cyclicBuffer[currentBufferIndex];
+ }
+ );
+
+ return snapshot;
+ }
+
private _increaseCapacityIfNecessary(): void {
const currCapacity = this._cyclicBuffer.length;
if (this._size < currCapacity) {
@@ -227,15 +256,12 @@ export class SlimQueue {
// In the new cyclic buffer we re-order items, such that head is located
// at index 0.
let newBufferLastOccupiedIndex = 0;
- for (let i = this._headIndex; i < this._cyclicBuffer.length; ++i) {
- newCyclicBuffer[newBufferLastOccupiedIndex++] = this._cyclicBuffer[i];
- this._cyclicBuffer[i] = undefined;
- }
-
- for (let i = 0; i < this._headIndex; ++i) {
- newCyclicBuffer[newBufferLastOccupiedIndex++] = this._cyclicBuffer[i];
- this._cyclicBuffer[i] = undefined;
- }
+ this._traverseInOrder(
+ (currentBufferIndex: number) => {
+ newCyclicBuffer[newBufferLastOccupiedIndex++] = this._cyclicBuffer[currentBufferIndex];
+ this._cyclicBuffer[currentBufferIndex] = undefined;
+ }
+ );
this._headIndex = 0;
this._cyclicBuffer = newCyclicBuffer;
@@ -253,18 +279,41 @@ export class SlimQueue {
private _validateCapacityIncrementFactor(factor: number): void {
if (factor < MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR) {
throw new Error(
- `Failed to instantiate SlimQueue due to a too-small capacityIncrementFactor of ` +
- `${factor}. The minimum allowed is ${MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR}`
+ `Failed to instantiate SlimQueue: The provided capacityIncrementFactor of ` +
+ `${factor} is too small. The minimum allowed value is ${MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR}`
);
}
if (factor > MAX_ALLOWED_CAPACITY_INCREMENT_FACTOR) {
throw new Error(
- `Failed to instantiate SlimQueue due to a too-large capacityIncrementFactor of ` +
- `${factor}. The maximum allowed is ${MAX_ALLOWED_CAPACITY_INCREMENT_FACTOR}`
+ `Failed to instantiate SlimQueue: The provided capacityIncrementFactor of ` +
+ `${factor} is too large. The maximum allowed value is ${MIN_ALLOWED_CAPACITY_INCREMENT_FACTOR}`
);
}
}
+
+ /**
+ * _traverseInOrder
+ *
+ * Facilitates traversing the items in the queue in order, from first-in to last-in.
+ * The method accepts a callback, which is invoked with the current item index in
+ * the internal cyclic buffer.
+ *
+ * @param callback The callback to execute, provided with the current item index.
+ */
+ private _traverseInOrder(callback: TraverseCallback): void {
+ let itemsTraversed = 0;
+ let currentBufferIndex = this._headIndex;
+
+ while (itemsTraversed < this._size) {
+ callback(currentBufferIndex);
+ ++itemsTraversed;
+
+ if (++currentBufferIndex === this._cyclicBuffer.length) {
+ currentBufferIndex = 0;
+ }
+ }
+ }
}
function isNaturalNumber(num: number): boolean {