Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Iterable queues #1556

Merged
merged 2 commits into from Jul 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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();
}
})
});