Skip to content

Commit 79a0d67

Browse files
linked queue w async iterators
1 parent d525630 commit 79a0d67

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

src/example.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
3+
import {LinkedQueue} from "./linked-queue";
4+
5+
(async () => {
6+
const queue = new LinkedQueue<number, string>();
7+
8+
queue.enqueue('a', 1);
9+
queue.enqueue('b', 2);
10+
queue.enqueue('c', 3);
11+
12+
console.log('Forward Async Iteration:');
13+
for await (const [key, value] of queue.asyncIterator()) {
14+
console.log(`Key: ${key}, Processed Value: ${value}`);
15+
}
16+
17+
console.log('Reverse Async Iteration:');
18+
for await (const [key, value] of queue.asyncReverseIterator()) {
19+
console.log(`Key: ${key}, Processed Value: ${value}`);
20+
}
21+
})();

src/linked-queue.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,37 @@ export class LinkedQueue<V, K = any> {
141141
}
142142
}
143143

144+
// Example async processing function for each item (replace with your own logic)
145+
private async processItem(key: K, value: V): Promise<V> {
146+
// Simulate an async task, e.g., fetching data or processing the item
147+
return new Promise((resolve) => {
148+
// Replace this with your actual async task
149+
setTimeout(() => {
150+
console.log(`Processing item with key: ${key}, value: ${value}`);
151+
resolve(value); // Return the value, processed if needed
152+
}, 100);
153+
});
154+
}
155+
156+
async *asyncIterator(): AsyncGenerator<[K, V], void, unknown> {
157+
let v = this.head;
158+
while (v) {
159+
const processedValue = await this.processItem(v.key, v.value); // Async processing per item
160+
yield [v.key, processedValue];
161+
v = v.after;
162+
}
163+
}
164+
165+
// Async iterator for reverse traversal
166+
async *asyncReverseIterator(): AsyncGenerator<[K, V], void, unknown> {
167+
let v = this.tail;
168+
while (v) {
169+
const processedValue = await this.processItem(v.key, v.value); // Async processing per item
170+
yield [v.key, processedValue];
171+
v = v.before;
172+
}
173+
}
174+
144175
dequeueIterator() {
145176

146177
const self = this;

tsconfig.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"allowUnreachableCode": true,
1515
"lib": [
1616
"es2019",
17-
"es2020"
17+
"es2020",
18+
"dom"
1819
]
1920
},
2021
"compileOnSave": false,

0 commit comments

Comments
 (0)