Skip to content

Commit

Permalink
feat: BlockedQueue
Browse files Browse the repository at this point in the history
  • Loading branch information
Soontao committed Apr 21, 2021
1 parent d843470 commit 413b1a7
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/functional/BlockedQueue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@


/**
* BlockedQueue
*
* provide a blocked queue for async operations
*
* @since 5.19.0
* @category Functional
*/
export class BlockedQueue<I = any> {

private _capacity: number;
private _notifyQueue: Array<Function>;

private _container: Array<I>;

constructor(capacity = 1000) {
this._capacity = capacity;
this._container = new Array(0);
this._notifyQueue = new Array(0);
}

async enQueue(item: I): Promise<void> {

if (this._container.length >= this._capacity) {

return new Promise((resolve) => {
this._notifyQueue.push(() => {
this._container.push(item);
resolve();
});
});

}

this._container.push(item);
return;

}

async deQueue(): Promise<I> {
if (this._container.length > 0) {
const item = this._container.shift();
if (this._notifyQueue.length > 0) {
this._notifyQueue.shift()();
}
return item;
}
return undefined;
}


}


export default BlockedQueue;
40 changes: 40 additions & 0 deletions test/functional.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { BlockedQueue } from '../src/functional/BlockedQueue';
import defineFunctionName from '../src/functional/defineFunctionName';
import { hash } from '../src/functional/hash';
import { hashEqual } from '../src/functional/hashEqual';
Expand Down Expand Up @@ -115,4 +116,43 @@ describe('functional', () => {

});

it('should support blocked queue', async () => {

const q = new BlockedQueue(3);
const seq = [];

const enQ = (v: any) => q.enQueue(v).then(() => seq.push(`p${v}`));
const deQ = () => q.deQueue().then((value) => { seq.push(`d${value}`); return value; });
const p1 = Promise.all([
enQ(1),
enQ(2),
enQ(3),
enQ(4)
]);

const p2 = Promise.all([
deQ(),
deQ(),
deQ(),
deQ(),
deQ()
]);

await Promise.all([p1, p2]);

expect(seq).toStrictEqual([
'p1',
'p2',
'p3',
'd1',
'd2',
'd3',
'd4',
'dundefined',
'p4'
]);


});

});

0 comments on commit 413b1a7

Please sign in to comment.