@anmiles/queue 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.js ADDED
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ root : true,
3
+ extends : [
4
+ './node_modules/@anmiles/eslint-config/.eslintrc.js',
5
+ ],
6
+ };
package/.gitlab-ci.yml ADDED
@@ -0,0 +1,117 @@
1
+ default:
2
+ image: node:18.14
3
+
4
+ stages:
5
+ - setup
6
+ - build
7
+ - test
8
+ - coverage
9
+ - deploy
10
+
11
+ install:
12
+ stage: setup
13
+ cache:
14
+ key:
15
+ files:
16
+ - package-lock.json
17
+ prefix: ${CI_COMMIT_REF_SLUG}
18
+ paths:
19
+ - node_modules
20
+ policy: pull-push
21
+ script:
22
+ - npm ci
23
+ only:
24
+ - main
25
+ - merge_requests
26
+
27
+ build:
28
+ stage: build
29
+ cache:
30
+ key:
31
+ files:
32
+ - package-lock.json
33
+ prefix: ${CI_COMMIT_REF_SLUG}
34
+ paths:
35
+ - node_modules
36
+ policy: pull
37
+ script:
38
+ - npm run build
39
+ artifacts:
40
+ paths:
41
+ - dist/
42
+ only:
43
+ - main
44
+ - merge_requests
45
+
46
+ lint:
47
+ stage: test
48
+ cache:
49
+ key:
50
+ files:
51
+ - package-lock.json
52
+ prefix: ${CI_COMMIT_REF_SLUG}
53
+ paths:
54
+ - node_modules
55
+ policy: pull
56
+ script:
57
+ - npm run lint
58
+ only:
59
+ - main
60
+ - merge_requests
61
+
62
+ test:
63
+ stage: test
64
+ cache:
65
+ - key:
66
+ files:
67
+ - package-lock.json
68
+ prefix: ${CI_COMMIT_REF_SLUG}
69
+ paths:
70
+ - node_modules
71
+ policy: pull
72
+ - key: ${CI_COMMIT_REF_SLUG}_coverage
73
+ paths:
74
+ - coverage/**/*
75
+ policy: push
76
+ script:
77
+ - npm run test:ci
78
+ only:
79
+ - main
80
+ - merge_requests
81
+
82
+ coverage:
83
+ stage: coverage
84
+ cache:
85
+ - key:
86
+ files:
87
+ - package-lock.json
88
+ prefix: ${CI_COMMIT_REF_SLUG}
89
+ paths:
90
+ - node_modules
91
+ policy: pull
92
+ - key: ${CI_COMMIT_REF_SLUG}_coverage
93
+ paths:
94
+ - coverage/**/*
95
+ policy: pull
96
+ script:
97
+ - npm run test:report:coverage
98
+ only:
99
+ - main
100
+ - merge_requests
101
+
102
+ publish:
103
+ stage: deploy
104
+ cache:
105
+ key:
106
+ files:
107
+ - package-lock.json
108
+ prefix: ${CI_COMMIT_REF_SLUG}
109
+ paths:
110
+ - node_modules
111
+ policy: pull
112
+ script:
113
+ - npm publish
114
+ when: manual
115
+ only:
116
+ - main
117
+ - merge_requests
@@ -0,0 +1,9 @@
1
+ {
2
+ "cSpell.words": [
3
+ "anmiles",
4
+ "cicd",
5
+ "emittery",
6
+ "linebreak",
7
+ "nycrc"
8
+ ]
9
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0](../../tags/v1.0.0) - 2023-05-07
9
+ ### Changed
10
+ - First release
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Anatoliy Oblaukhov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # @anmiles/queue
2
+
3
+ Queue dispatcher that sequentially processes incoming items
4
+
5
+ ----
6
+
7
+ ## Installation
8
+
9
+ `npm install @anmiles/queue`
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import Queue from '@anmiles/queue';
15
+
16
+ const queue = new Queue([ item1, item2, item3 ], { interval: 500 });
17
+ queue.on('item', (item) => console.log('queue accessed this item in 500ms after previous one', item));
18
+ queue.on('done', () => console.log('queue finished'));
19
+ queue.dequeue();
20
+
21
+ /* after some time */
22
+ queue.enqueue([ item4, item5 ]);
23
+ /* queue automatically gets dequeued new items here */
24
+ ```
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ 'check-coverage' : true,
3
+ 'statements' : 100,
4
+ 'branches' : 100,
5
+ 'lines' : 100,
6
+ 'functions' : 100,
7
+ 'reporter' : [ 'html', 'text' ],
8
+ };
@@ -0,0 +1 @@
1
+ export { default } from './lib/queue';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = void 0;
7
+ var queue_1 = require("./lib/queue");
8
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(queue_1).default; } });
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,qCAAsC;AAA7B,iHAAA,OAAO,OAAA"}
@@ -0,0 +1,19 @@
1
+ import Emittery from 'emittery';
2
+ type Listeners<T> = {
3
+ item: (item: T) => Promise<void>;
4
+ done: () => void;
5
+ };
6
+ export default class Queue<TItem> extends Emittery<{
7
+ [TEvent in keyof Listeners<TItem>]: Parameters<Listeners<TItem>[TEvent]>[0];
8
+ }> {
9
+ private done;
10
+ private data;
11
+ private interval;
12
+ constructor(data?: TItem[], { interval }?: {
13
+ interval?: number;
14
+ });
15
+ enqueue(...items: TItem[]): Queue<TItem>;
16
+ dequeue(): Promise<void>;
17
+ count(): number;
18
+ }
19
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const emittery_1 = __importDefault(require("emittery"));
7
+ class Queue extends emittery_1.default {
8
+ constructor(data = [], { interval = 0 } = {}) {
9
+ super();
10
+ this.data = data;
11
+ this.interval = interval;
12
+ }
13
+ enqueue(...items) {
14
+ this.data.push(...items);
15
+ if (this.done) {
16
+ this.dequeue();
17
+ }
18
+ return this;
19
+ }
20
+ async dequeue() {
21
+ this.done = false;
22
+ if (this.data.length > 0) {
23
+ const now = performance.now();
24
+ await this.emit('item', this.data.shift());
25
+ setTimeout(() => this.dequeue(), Math.max(0, this.interval - (performance.now() - now)));
26
+ }
27
+ else {
28
+ this.done = true;
29
+ this.emit('done');
30
+ }
31
+ }
32
+ count() {
33
+ return this.data.length;
34
+ }
35
+ }
36
+ exports.default = Queue;
37
+ //# sourceMappingURL=queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue.js","sourceRoot":"","sources":["../../src/lib/queue.ts"],"names":[],"mappings":";;;;;AAAA,wDAAgC;AAOhC,MAAqB,KAAa,SAAQ,kBAAuF;IAKhI,YAAY,OAAgB,EAAE,EAAE,EAAE,QAAQ,GAAG,CAAC,KAA4B,EAAE;QAC3E,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,IAAI,GAAO,IAAI,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;IAED,OAAO,CAAC,GAAG,KAAc;QACxB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAEzB,IAAI,IAAI,CAAC,IAAI,EAAE;YACd,IAAI,CAAC,OAAO,EAAE,CAAC;SACf;QAED,OAAO,IAAI,CAAC;IACb,CAAC;IAED,KAAK,CAAC,OAAO;QACZ,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC;QAElB,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;YACzB,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;YAC9B,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAW,CAAC,CAAC;YACpD,UAAU,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,QAAQ,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;SACzF;aAAM;YACN,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;YACjB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SAClB;IACF,CAAC;IAED,KAAK;QACJ,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;IACzB,CAAC;CACD;AArCD,wBAqCC"}
package/jest.config.js ADDED
@@ -0,0 +1,22 @@
1
+ module.exports = {
2
+ preset : 'ts-jest',
3
+ clearMocks : true,
4
+
5
+ roots : [ '<rootDir>/src' ],
6
+ testMatch : [ '<rootDir>/src/**/__tests__/*.test.ts' ],
7
+ transform : {
8
+ '^.+\\.ts$' : 'ts-jest',
9
+ },
10
+ collectCoverageFrom : [
11
+ '<rootDir>/src/**/*.ts',
12
+ '!<rootDir>/src/**/*.d.ts',
13
+ '!<rootDir>/src/*.ts',
14
+ '!<rootDir>/src/types/*.ts',
15
+
16
+ '!**/node_modules/**',
17
+ '!**/__tests__/**',
18
+
19
+ '!<rootDir>/coverage/**',
20
+ '!<rootDir>/dist/**',
21
+ ],
22
+ };
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@anmiles/queue",
3
+ "version": "1.0.0",
4
+ "description": "Queue dispatcher that sequentially processes incoming items",
5
+ "keywords": [
6
+ "queue",
7
+ "enqueue",
8
+ "dispatcher"
9
+ ],
10
+ "author": "Anatoliy Oblaukhov",
11
+ "homepage": "https://gitlab.com/anmiles/lib/queue",
12
+ "repository": "gitlab:anmiles/lib/queue",
13
+ "license": "MIT",
14
+ "engines": {
15
+ "node": ">=18.14.2"
16
+ },
17
+ "main": "dist/index.js",
18
+ "scripts": {
19
+ "build": "rimraf dist && tsc",
20
+ "lint": "eslint --ext .js,.ts .",
21
+ "lint:fix": "npm run lint -- --fix",
22
+ "test": "jest --verbose",
23
+ "test:coverage": "npm test -- --coverage",
24
+ "test:ci": "npm test -- --ci --coverage",
25
+ "test:watch": "npm test -- --watch",
26
+ "test:watch:coverage": "npm test -- --watch --coverage",
27
+ "test:report:coverage": "nyc report --nycrc-path ./coverage.config.js -t ./coverage --report-dir ./coverage"
28
+ },
29
+ "dependencies": {
30
+ "emittery": "^0.13.1"
31
+ },
32
+ "devDependencies": {
33
+ "@anmiles/eslint-config": "^1.0.4",
34
+ "@anmiles/sleep": "^1.0.0",
35
+ "@types/jest": "^29.5.1",
36
+ "@typescript-eslint/eslint-plugin": "^5.59.2",
37
+ "@typescript-eslint/parser": "^5.59.2",
38
+ "eslint": "^8.40.0",
39
+ "eslint-plugin-align-assignments": "^1.1.2",
40
+ "eslint-plugin-import": "^2.27.5",
41
+ "eslint-plugin-jest": "^27.2.1",
42
+ "jest": "^29.5.0",
43
+ "nyc": "^15.1.0",
44
+ "rimraf": "^5.0.0",
45
+ "ts-jest": "^29.1.0",
46
+ "typescript": "^5.0.4"
47
+ }
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from './lib/queue';
@@ -0,0 +1,445 @@
1
+ import sleep from '@anmiles/sleep';
2
+ import Queue from '../queue';
3
+
4
+ describe('src/lib/queue', () => {
5
+ let queue: Queue<number>;
6
+ let log: string[];
7
+
8
+ beforeEach(() => {
9
+ queue = new Queue([ 500, 400 ]);
10
+ log = [];
11
+ });
12
+
13
+ const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
14
+
15
+ beforeEach(() => {
16
+ setTimeoutSpy.mockImplementation((func, timeout) => {
17
+ log.push(`timeout(${Math.floor(timeout || 0)})`);
18
+ func();
19
+ return 0 as unknown as ReturnType<typeof setTimeout>;
20
+ });
21
+ });
22
+
23
+ afterAll(() => {
24
+ setTimeoutSpy.mockRestore();
25
+ });
26
+
27
+ describe('constructor', () => {
28
+ describe('data', () => {
29
+ it('should be empty array by default', () => {
30
+ expect(new Queue()['data']).toEqual([]);
31
+ });
32
+
33
+ it('should be set if specified', () => {
34
+ expect(new Queue([ 3, 4, 5 ])['data']).toEqual([ 3, 4, 5 ]);
35
+ });
36
+ });
37
+
38
+ describe('interval', () => {
39
+ it('should be 0 by default', () => {
40
+ expect(new Queue()['interval']).toEqual(0);
41
+ });
42
+
43
+ it('should be set if specified', () => {
44
+ expect(new Queue([], { interval : 10 })['interval']).toEqual(10);
45
+ });
46
+ });
47
+ });
48
+
49
+ describe('sync', () => {
50
+ beforeEach(() => {
51
+ queue.on('item', (item) => {
52
+ log.push(`item(${item})`);
53
+ });
54
+ });
55
+
56
+ it('should process empty queue', () => new Promise<void>((resolve) => {
57
+ queue['data'] = [];
58
+
59
+ queue.on('done', () => {
60
+ log.push('done');
61
+
62
+ expect(log).toEqual([
63
+ 'done',
64
+ ]);
65
+
66
+ resolve();
67
+ });
68
+
69
+ queue.dequeue();
70
+ }));
71
+
72
+ it('should process queue in sequential order', () => new Promise<void>((resolve) => {
73
+ queue.on('done', () => {
74
+ log.push('done');
75
+
76
+ expect(log).toEqual([
77
+ 'item(500)',
78
+ 'timeout(0)',
79
+ 'item(400)',
80
+ 'timeout(0)',
81
+ 'done',
82
+ ]);
83
+
84
+ resolve();
85
+ });
86
+
87
+ queue.dequeue();
88
+ }));
89
+
90
+ it('should process queue with intervals in sequential order', () => new Promise<void>((resolve) => {
91
+ queue['interval'] = 1000;
92
+
93
+ queue.on('done', () => {
94
+ log.push('done');
95
+
96
+ expect(log).toEqual([
97
+ 'item(500)',
98
+ 'timeout(999)',
99
+ 'item(400)',
100
+ 'timeout(999)',
101
+ 'done',
102
+ ]);
103
+
104
+ resolve();
105
+ });
106
+
107
+ queue.dequeue();
108
+ }));
109
+
110
+ it('should process queue in sequential order when enqueuing items before dequeueing', () => new Promise<void>((resolve) => {
111
+ queue.on('done', () => {
112
+ log.push('done');
113
+
114
+ expect(log).toEqual([
115
+ 'item(500)',
116
+ 'timeout(0)',
117
+ 'item(400)',
118
+ 'timeout(0)',
119
+ 'item(300)',
120
+ 'timeout(0)',
121
+ 'item(200)',
122
+ 'timeout(0)',
123
+ 'done',
124
+ ]);
125
+
126
+ resolve();
127
+ });
128
+
129
+ queue.enqueue(300, 200);
130
+ queue.dequeue();
131
+ }));
132
+
133
+ it('should process queue in sequential order when enqueuing items after dequeueing', () => new Promise<void>((resolve) => {
134
+ let doneCalledOnce = false;
135
+
136
+ queue.on('done', () => {
137
+ log.push('done');
138
+
139
+ if (!doneCalledOnce) {
140
+ doneCalledOnce = true;
141
+ queue.enqueue(300, 200);
142
+ return;
143
+ }
144
+
145
+ expect(log).toEqual([
146
+ 'item(500)',
147
+ 'timeout(0)',
148
+ 'item(400)',
149
+ 'timeout(0)',
150
+ 'done',
151
+ 'item(300)',
152
+ 'timeout(0)',
153
+ 'item(200)',
154
+ 'timeout(0)',
155
+ 'done',
156
+ ]);
157
+
158
+ resolve();
159
+ });
160
+
161
+ queue.dequeue();
162
+ }));
163
+
164
+ it('should process queue with intervals in sequential order when enqueuing items before dequeueing', () => new Promise<void>((resolve) => {
165
+ queue['interval'] = 1000;
166
+
167
+ queue.on('done', () => {
168
+ log.push('done');
169
+
170
+ expect(log).toEqual([
171
+ 'item(500)',
172
+ 'timeout(999)',
173
+ 'item(400)',
174
+ 'timeout(999)',
175
+ 'item(300)',
176
+ 'timeout(999)',
177
+ 'item(200)',
178
+ 'timeout(999)',
179
+ 'done',
180
+ ]);
181
+
182
+ resolve();
183
+ });
184
+
185
+ queue.enqueue(300, 200);
186
+ queue.dequeue();
187
+ }));
188
+
189
+ it('should process queue with intervals in sequential order when enqueuing items after dequeueing', () => new Promise<void>((resolve) => {
190
+ queue['interval'] = 1000;
191
+
192
+ let doneCalledOnce = false;
193
+
194
+ queue.on('done', () => {
195
+ log.push('done');
196
+
197
+ if (!doneCalledOnce) {
198
+ doneCalledOnce = true;
199
+ queue.enqueue(300, 200);
200
+ return;
201
+ }
202
+
203
+ expect(log).toEqual([
204
+ 'item(500)',
205
+ 'timeout(999)',
206
+ 'item(400)',
207
+ 'timeout(999)',
208
+ 'done',
209
+ 'item(300)',
210
+ 'timeout(999)',
211
+ 'item(200)',
212
+ 'timeout(999)',
213
+ 'done',
214
+ ]);
215
+
216
+ resolve();
217
+ });
218
+
219
+ queue.dequeue();
220
+ }));
221
+ });
222
+
223
+ describe('async', () => {
224
+ beforeEach(() => {
225
+ queue.on('item', async (item) => {
226
+ log.push(`before(${item})`);
227
+ await sleep(item || 0);
228
+ log.push(`after(${item})`);
229
+ });
230
+ });
231
+
232
+ it('should process empty queue', () => new Promise<void>((resolve) => {
233
+ queue['data'] = [];
234
+
235
+ queue.on('done', () => {
236
+ log.push('done');
237
+
238
+ expect(log).toEqual([
239
+ 'done',
240
+ ]);
241
+
242
+ resolve();
243
+ });
244
+
245
+ queue.dequeue();
246
+ }));
247
+
248
+ it('should process queue in sequential order', () => new Promise<void>((resolve) => {
249
+ queue.on('done', () => {
250
+ log.push('done');
251
+
252
+ expect(log).toEqual([
253
+ 'before(500)',
254
+ 'timeout(500)',
255
+ 'after(500)',
256
+ 'timeout(0)',
257
+ 'before(400)',
258
+ 'timeout(400)',
259
+ 'after(400)',
260
+ 'timeout(0)',
261
+ 'done',
262
+ ]);
263
+
264
+ resolve();
265
+ });
266
+
267
+ queue.dequeue();
268
+ }));
269
+
270
+ it('should process queue with intervals in sequential order', () => new Promise<void>((resolve) => {
271
+ queue['interval'] = 1000;
272
+
273
+ queue.on('done', () => {
274
+ log.push('done');
275
+
276
+ expect(log).toEqual([
277
+ 'before(500)',
278
+ 'timeout(500)',
279
+ 'after(500)',
280
+ 'timeout(999)',
281
+ 'before(400)',
282
+ 'timeout(400)',
283
+ 'after(400)',
284
+ 'timeout(999)',
285
+ 'done',
286
+ ]);
287
+
288
+ resolve();
289
+ });
290
+
291
+ queue.dequeue();
292
+ }));
293
+
294
+ it('should process queue in sequential order when enqueuing items before dequeueing', () => new Promise<void>((resolve) => {
295
+ queue.on('done', () => {
296
+ log.push('done');
297
+
298
+ expect(log).toEqual([
299
+ 'before(500)',
300
+ 'timeout(500)',
301
+ 'after(500)',
302
+ 'timeout(0)',
303
+ 'before(400)',
304
+ 'timeout(400)',
305
+ 'after(400)',
306
+ 'timeout(0)',
307
+ 'before(300)',
308
+ 'timeout(300)',
309
+ 'after(300)',
310
+ 'timeout(0)',
311
+ 'before(200)',
312
+ 'timeout(200)',
313
+ 'after(200)',
314
+ 'timeout(0)',
315
+ 'done',
316
+ ]);
317
+
318
+ resolve();
319
+ });
320
+
321
+ queue.enqueue(300, 200);
322
+ queue.dequeue();
323
+ }));
324
+
325
+ it('should process queue in sequential order when enqueuing items after dequeueing', () => new Promise<void>((resolve) => {
326
+ let doneCalledOnce = false;
327
+
328
+ queue.on('done', () => {
329
+ log.push('done');
330
+
331
+ if (!doneCalledOnce) {
332
+ doneCalledOnce = true;
333
+ queue.enqueue(300, 200);
334
+ return;
335
+ }
336
+
337
+ expect(log).toEqual([
338
+ 'before(500)',
339
+ 'timeout(500)',
340
+ 'after(500)',
341
+ 'timeout(0)',
342
+ 'before(400)',
343
+ 'timeout(400)',
344
+ 'after(400)',
345
+ 'timeout(0)',
346
+ 'done',
347
+ 'before(300)',
348
+ 'timeout(300)',
349
+ 'after(300)',
350
+ 'timeout(0)',
351
+ 'before(200)',
352
+ 'timeout(200)',
353
+ 'after(200)',
354
+ 'timeout(0)',
355
+ 'done',
356
+ ]);
357
+
358
+ resolve();
359
+ });
360
+
361
+ queue.dequeue();
362
+ }));
363
+
364
+ it('should process queue with intervals in sequential order when enqueuing items before dequeueing', () => new Promise<void>((resolve) => {
365
+ queue['interval'] = 1000;
366
+
367
+ queue.on('done', () => {
368
+ log.push('done');
369
+
370
+ expect(log).toEqual([
371
+ 'before(500)',
372
+ 'timeout(500)',
373
+ 'after(500)',
374
+ 'timeout(999)',
375
+ 'before(400)',
376
+ 'timeout(400)',
377
+ 'after(400)',
378
+ 'timeout(999)',
379
+ 'before(300)',
380
+ 'timeout(300)',
381
+ 'after(300)',
382
+ 'timeout(999)',
383
+ 'before(200)',
384
+ 'timeout(200)',
385
+ 'after(200)',
386
+ 'timeout(999)',
387
+ 'done',
388
+ ]);
389
+
390
+ resolve();
391
+ });
392
+
393
+ queue.enqueue(300, 200);
394
+ queue.dequeue();
395
+ }));
396
+
397
+ it('should process queue with intervals in sequential order when enqueuing items after dequeueing', () => new Promise<void>((resolve) => {
398
+ queue['interval'] = 1000;
399
+
400
+ let doneCalledOnce = false;
401
+
402
+ queue.on('done', () => {
403
+ log.push('done');
404
+
405
+ if (!doneCalledOnce) {
406
+ doneCalledOnce = true;
407
+ queue.enqueue(300, 200);
408
+ return;
409
+ }
410
+
411
+ expect(log).toEqual([
412
+ 'before(500)',
413
+ 'timeout(500)',
414
+ 'after(500)',
415
+ 'timeout(999)',
416
+ 'before(400)',
417
+ 'timeout(400)',
418
+ 'after(400)',
419
+ 'timeout(999)',
420
+ 'done',
421
+ 'before(300)',
422
+ 'timeout(300)',
423
+ 'after(300)',
424
+ 'timeout(999)',
425
+ 'before(200)',
426
+ 'timeout(200)',
427
+ 'after(200)',
428
+ 'timeout(999)',
429
+ 'done',
430
+ ]);
431
+
432
+ resolve();
433
+ });
434
+
435
+ queue.dequeue();
436
+ }));
437
+ });
438
+
439
+ describe('count', () => {
440
+ it('return count of data', () => {
441
+ expect(queue.count()).toEqual(2);
442
+ });
443
+ });
444
+ });
445
+
@@ -0,0 +1,45 @@
1
+ import Emittery from 'emittery';
2
+
3
+ type Listeners<T> = {
4
+ item: (item: T) => Promise<void>;
5
+ done: () => void;
6
+ }
7
+
8
+ export default class Queue<TItem> extends Emittery<{[TEvent in keyof Listeners<TItem>]: Parameters<Listeners<TItem>[TEvent]>[0]}> {
9
+ private done: boolean;
10
+ private data: TItem[];
11
+ private interval: number;
12
+
13
+ constructor(data: TItem[] = [], { interval = 0 }: { interval?: number } = {}) {
14
+ super();
15
+ this.data = data;
16
+ this.interval = interval;
17
+ }
18
+
19
+ enqueue(...items: TItem[]): Queue<TItem> {
20
+ this.data.push(...items);
21
+
22
+ if (this.done) {
23
+ this.dequeue();
24
+ }
25
+
26
+ return this;
27
+ }
28
+
29
+ async dequeue(): Promise<void> {
30
+ this.done = false;
31
+
32
+ if (this.data.length > 0) {
33
+ const now = performance.now();
34
+ await this.emit('item', this.data.shift() as TItem);
35
+ setTimeout(() => this.dequeue(), Math.max(0, this.interval - (performance.now() - now)));
36
+ } else {
37
+ this.done = true;
38
+ this.emit('done');
39
+ }
40
+ }
41
+
42
+ count(): number {
43
+ return this.data.length;
44
+ }
45
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "CommonJS",
4
+ "target": "ES2019",
5
+
6
+ "moduleResolution": "node",
7
+ "resolveJsonModule": true,
8
+
9
+ "rootDir": "./src",
10
+ "outDir": "./dist",
11
+
12
+ "allowJs": false,
13
+ "sourceMap": true,
14
+ "declaration": true,
15
+ "noImplicitAny": true,
16
+ "esModuleInterop": true,
17
+ "strictNullChecks": true,
18
+ "allowSyntheticDefaultImports": true,
19
+ },
20
+ "exclude": [
21
+ "**/node_modules/",
22
+ "**/__tests__/",
23
+ "coverage/",
24
+ "dist/",
25
+ ],
26
+ }