Skip to content

Commit

Permalink
feat: Iterable queues (#1556)
Browse files Browse the repository at this point in the history
* feat: iterable queues

* docs
  • Loading branch information
aearly committed Jul 9, 2018
1 parent 17471a5 commit 1f3925e
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 8 deletions.
16 changes: 9 additions & 7 deletions lib/internal/DoublyLinkedList.js
Expand Up @@ -60,14 +60,16 @@ export default class DLL {
return this.tail && this.removeLink(this.tail);
}

toArray () {
var arr = Array(this.length);
var curr = this.head;
for(var idx = 0; idx < this.length; idx++) {
arr[idx] = curr.data;
curr = curr.next;
toArray() {
return [...this]
}

*[Symbol.iterator] () {
var cur = this.head
while (cur) {
yield cur.data
cur = cur.next
}
return arr;
}

remove (testFn) {
Expand Down
3 changes: 3 additions & 0 deletions lib/internal/queue.js
Expand Up @@ -87,6 +87,9 @@ export default function queue(worker, concurrency, payload) {
var isProcessing = false;
var q = {
_tasks: new DLL(),
*[Symbol.iterator] () {
yield* q._tasks[Symbol.iterator]()
},
concurrency,
payload,
saturated: noop,
Expand Down
14 changes: 13 additions & 1 deletion lib/queue.js
Expand Up @@ -3,7 +3,7 @@ import wrapAsync from './internal/wrapAsync';

/**
* A queue of tasks for the worker function to complete.
* @typedef {Object} QueueObject
* @typedef {Iterable} QueueObject
* @memberOf module:ControlFlow
* @property {Function} length - a function returning the number of items
* waiting to be processed. Invoke with `queue.length()`.
Expand Down Expand Up @@ -53,6 +53,18 @@ import wrapAsync from './internal/wrapAsync';
* @property {Function} kill - a function that removes the `drain` callback and
* empties remaining tasks from the queue forcing it to go idle. No more tasks
* should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
*
* @example
* const q = aync.queue(worker, 2)
* q.push(item1)
* q.push(item2)
* q.push(item3)
* // queues are iterable, spread into an array to inspect
* const items = [...q] // [item1, item2, item3]
* // or use for of
* for (let item of q) {
* console.log(item)
* }
*/

/**
Expand Down
19 changes: 19 additions & 0 deletions test/queue.js
Expand Up @@ -799,4 +799,23 @@ describe('queue', function(){
done();
}
});

it('should be iterable', (done) => {
var q = async.queue((data, cb) => {
if (data === 3) {
q.push(6)
expect([...q]).to.eql([4, 5, 6]);
}
async.setImmediate(cb);
});

q.push([1, 2, 3, 4, 5]);

expect([...q]).to.eql([1, 2, 3, 4, 5]);

q.drain = function () {
expect([...q]).to.eql([]);
done();
}
})
});

0 comments on commit 1f3925e

Please sign in to comment.