stardust-parallel-js 1.0.10 β†’ 1.2.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/README.md CHANGED
@@ -1,310 +1,306 @@
1
- # ⚑ stardust-parallel-js
2
-
3
- [![npm version](https://img.shields.io/npm/v/stardust-parallel-js.svg)](https://www.npmjs.com/package/stardust-parallel-js)
4
- [![npm downloads](https://img.shields.io/npm/dm/stardust-parallel-js.svg)](https://www.npmjs.com/package/stardust-parallel-js)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
6
- [![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/b1411/5e96225d1a326e23a38edc41799b1ead/raw/coverage.json)](https://github.com/b1411/parallel.js)
7
- [![Node.js Version](https://img.shields.io/node/v/stardust-parallel-js.svg)](https://nodejs.org)
8
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue.svg)](https://www.typescriptlang.org/)
9
- [![Bundle Size](https://img.shields.io/bundlephobia/minzip/stardust-parallel-js)](https://bundlephobia.com/package/stardust-parallel-js)
10
- [![GitHub stars](https://img.shields.io/github/stars/b1411/parallel.js.svg?style=social)](https://github.com/b1411/parallel.js)
11
-
12
- > πŸ“– **Other languages:** [Русский](./README.ru.md)
13
-
14
- **Speed up your Node.js applications up to 3x** with a simple API for parallel task execution!
15
-
16
- A library for parallel execution of JavaScript/TypeScript functions using Worker Threads in Node.js.
17
-
18
- ## πŸš€ Performance
19
-
20
- Real benchmarks on 4-core CPU:
21
-
22
- | Task | Sequential | Parallel (4 workers) | Speedup |
23
- |------|-----------|---------------------|---------|
24
- | **Fibonacci(35-42) computation** | 5113 ms | 2606 ms | **1.96x** πŸ”₯ |
25
- | **Processing 50 items** | 936 ms | 344 ms | **2.72x** ⚑ |
26
-
27
- > πŸ’‘ **Result**: up to **63% performance improvement** on CPU-intensive tasks!
28
-
29
- ## ✨ Features
30
-
31
- - πŸš€ **Up to 3x faster** - real speedup on multi-core processors
32
- - πŸ’‘ **Simple API** - start using in 2 minutes
33
- - πŸ”„ **Thread pool** - efficient resource management
34
- - ⚑ **Single threads** - for one-off tasks
35
- - πŸ“¦ **TypeScript** - full support out of the box
36
- - πŸ›‘οΈ **Reliability** - automatic recovery of crashed threads
37
- - 🎯 **Simplicity** - works like regular `map()`, but parallel
38
-
39
- ## πŸ“¦ Installation
40
-
41
- ```bash
42
- npm install stardust-parallel-js
43
- # or
44
- pnpm install stardust-parallel-js
45
- # or
46
- yarn add stardust-parallel-js
47
- ```
48
-
49
- ## 🎯 Quick Start
50
-
51
- **In 30 seconds** you can speed up array processing by 2-3x:
52
-
53
- ```typescript
54
- import { ThreadPool } from 'stardust-parallel-js';
55
-
56
- const pool = new ThreadPool(4);
57
-
58
- // Regular code - slow 🐌
59
- const results = data.map(item => heavyComputation(item));
60
-
61
- // With stardust-parallel-js - fast! ⚑
62
- const results = await pool.map(data, item => heavyComputation(item));
63
-
64
- await pool.terminate();
65
- ```
66
-
67
- **That's it!** Your code now runs in parallel on all CPU cores.
68
-
69
- ## πŸ“š Usage
70
-
71
- ### ThreadPool - Thread pool (recommended)
72
-
73
- Use `ThreadPool` to process multiple tasks with maximum efficiency:
74
-
75
- ```typescript
76
- import { ThreadPool } from 'stardust-parallel-js';
77
-
78
- // Create a pool of 4 threads (matching CPU cores)
79
- const pool = new ThreadPool(4);
80
-
81
- // 🎯 Process array - like regular map(), but parallel!
82
- const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
83
- const squares = await pool.map(numbers, (n: number) => n * n);
84
- console.log(squares); // [1, 4, 9, 16, 25, 36, 49, 64]
85
-
86
- // πŸ’ͺ CPU-intensive computations
87
- const result = await pool.execute(
88
- (n: number) => {
89
- let sum = 0;
90
- for (let i = 0; i < n; i++) {
91
- sum += Math.sqrt(i);
92
- }
93
- return sum;
94
- },
95
- [1000000]
96
- );
97
-
98
- // Release resources
99
- await pool.terminate();
100
- ```
101
-
102
- ### Thread - Single thread (for simple tasks)
103
-
104
- Use `Thread` for one-off operations:
105
-
106
- ```typescript
107
- import { Thread } from 'stardust-parallel-js';
108
-
109
- // Start and wait for result
110
- const thread = new Thread(
111
- (text: string) => text.toUpperCase(),
112
- ['hello world']
113
- );
114
-
115
- const result = await thread.join();
116
- console.log(result); // "HELLO WORLD"
117
-
118
- // Arrow functions work!
119
- const thread2 = new Thread(x => x * 2, [21]);
120
- console.log(await thread2.join()); // 42
121
- ```
122
-
123
- ## πŸ’‘ Real-World Examples
124
-
125
- ### Image Processing
126
-
127
- ```typescript
128
- import { ThreadPool } from 'stardust-parallel-js';
129
-
130
- const pool = new ThreadPool(8);
131
- const images = ['img1.jpg', 'img2.jpg', /* ... */ 'img100.jpg'];
132
-
133
- // Process 100 images in parallel
134
- const processed = await pool.map(images, (path: string) => {
135
- const fs = require('fs');
136
- const sharp = require('sharp');
137
- // Complex image processing
138
- return processImage(path);
139
- });
140
-
141
- await pool.terminate();
142
- ```
143
-
144
- ### Parsing Large Data
145
-
146
- ```typescript
147
- const pool = new ThreadPool(4);
148
- const chunks = splitDataIntoChunks(bigData, 1000);
149
-
150
- // Parse each chunk in parallel
151
- const parsed = await pool.map(chunks, (chunk: any[]) => {
152
- return chunk.map(item => parseComplexData(item));
153
- });
154
-
155
- await pool.terminate();
156
- ```
157
-
158
- ### Calculations and Analytics
159
-
160
- ```typescript
161
- const pool = new ThreadPool(4);
162
-
163
- const results = await pool.map([35, 36, 37, 38, 39, 40], n => {
164
- function fibonacci(num: number): number {
165
- if (num <= 1) return num;
166
- return fibonacci(num - 1) + fibonacci(num - 2);
167
- }
168
- return fibonacci(n);
169
- });
170
-
171
- await pool.terminate();
172
- ```
173
-
174
- ## πŸ“Š Benchmarks
175
-
176
- Run yourself and see the performance:
177
-
178
- ```bash
179
- npm run build
180
- npx tsx benchmarks/cpu-intensive.ts
181
- npx tsx benchmarks/data-processing.ts
182
- ```
183
-
184
- ## πŸŽ“ API Reference
185
-
186
- ### ThreadPool
187
-
188
- #### `constructor(size: number)`
189
- Creates a thread pool of the specified size.
190
-
191
- ```typescript
192
- const pool = new ThreadPool(4);
193
- ```
194
-
195
- #### `execute<TArgs, TResult>(fn: (...args: TArgs) => TResult, args?: TArgs): Promise<TResult>`
196
- Executes a function in an available thread from the pool.
197
-
198
- ```typescript
199
- const result = await pool.execute((x: number) => x * x, [5]);
200
- ```
201
-
202
- #### `map<T, R>(items: T[], fn: (item: T) => R): Promise<R[]>`
203
- Applies a function to each array element in parallel.
204
-
205
- ```typescript
206
- // Arrow function
207
- const results = await pool.map([1, 2, 3], n => n * 2);
208
-
209
- // Regular function
210
- const results2 = await pool.map([1, 2, 3], function(n) { return n * 2; });
211
- ```
212
-
213
- #### `terminate(): Promise<void>`
214
- Stops all threads and releases resources.
215
-
216
- ```typescript
217
- await pool.terminate();
218
- ```
219
-
220
- ### Thread
221
-
222
- #### `constructor<T, TArgs>(fn: (...args: TArgs) => T, args?: TArgs)`
223
- Creates a new thread to execute a function.
224
-
225
- ```typescript
226
- const thread = new Thread((x: number) => x * x, [5]);
227
- ```
228
-
229
- #### `join(): Promise<T>`
230
- Waits for execution to complete and returns the result. Automatically terminates the thread.
231
-
232
- ```typescript
233
- const result = await thread.join();
234
- ```
235
-
236
- ## ⚠️ Important Notes
237
-
238
- - πŸ”’ Functions execute in an isolated context (separate Worker Thread)
239
- - πŸ“¦ Arguments and results must be serializable
240
- - 🚫 Closures don't work - functions have no access to external variables
241
- - βœ… Regular and arrow functions are supported
242
- - βœ… `require()` is available inside functions for using Node.js modules
243
- - ⚑ Best suited for CPU-intensive tasks (calculations, data processing)
244
- - πŸ’‘ For I/O operations (reading files, network) use async/await instead of threads
245
-
246
- ## 🎯 When to Use?
247
-
248
- **βœ… Use stardust-parallel-js when:**
249
- - Processing large data arrays
250
- - Performing complex calculations
251
- - Parsing or transforming data
252
- - Processing images/video
253
- - Need to utilize all CPU cores
254
-
255
- **❌ Don't use when:**
256
- - Simple operations (faster to execute sequentially)
257
- - I/O operations (files, network, DB) - they're already asynchronous
258
- - Working with DOM (Node.js only)
259
-
260
- ## πŸ“ˆ How to Choose Pool Size?
261
-
262
- ```typescript
263
- import os from 'os';
264
-
265
- // Optimal: number of CPU cores
266
- const pool = new ThreadPool(os.cpus().length);
267
-
268
- // For CPU-intensive tasks
269
- const pool = new ThreadPool(os.cpus().length - 1); // leave 1 core for system
270
-
271
- // For mixed workload
272
- const pool = new ThreadPool(os.cpus().length * 2);
273
- ```
274
-
275
- ## 🀝 Comparison with Alternatives
276
-
277
- | Solution | Simplicity | Performance | TypeScript | Size |
278
- |----------|-----------|-------------|------------|------|
279
- | **stardust-parallel-js** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | βœ… Full | 9.3kB |
280
- | worker_threads | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⚠️ Partial | Built-in |
281
- | cluster | ⭐⭐ | ⭐⭐⭐ | ⚠️ Partial | Built-in |
282
- | child_process | ⭐ | ⭐⭐ | ❌ No | Built-in |
283
-
284
- ## πŸš€ Roadmap
285
-
286
- - [ ] Support for transferable objects for large data
287
- - [ ] Automatic selection of optimal pool size
288
- - [ ] Task prioritization
289
- - [ ] Monitoring and statistics
290
- - [ ] Support for async functions in threads
291
-
292
- ## πŸ’¬ Feedback
293
-
294
- Found a bug? Have an idea? [Create an issue](https://github.com/b1411/parallel.js)!
295
-
296
- ⭐ If the library helped you - give it a star on [GitHub](https://github.com/b1411/parallel.js)!
297
-
298
- ## πŸ“¦ Requirements
299
-
300
- - Node.js >= 14.0.0 (with Worker Threads support)
301
-
302
- ## πŸ“„ License
303
-
304
- MIT Β© [b1411](https://github.com/b1411)
305
-
306
- ---
307
-
308
- <p align="center">
309
- Made with ❀️ for the Node.js community
310
- </p>
1
+ # ⚑ stardust-parallel-js
2
+
3
+ [![npm version](https://img.shields.io/npm/v/stardust-parallel-js.svg)](https://www.npmjs.com/package/stardust-parallel-js)
4
+ [![npm downloads](https://img.shields.io/npm/dm/stardust-parallel-js.svg)](https://www.npmjs.com/package/stardust-parallel-js)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
6
+ [![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/b1411/5e96225d1a326e23a38edc41799b1ead/raw/coverage.json)](https://github.com/b1411/parallel.js)
7
+ [![Node.js Version](https://img.shields.io/node/v/stardust-parallel-js.svg)](https://nodejs.org)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue.svg)](https://www.typescriptlang.org/)
9
+ [![Bundle Size](https://img.shields.io/bundlephobia/minzip/stardust-parallel-js)](https://bundlephobia.com/package/stardust-parallel-js)
10
+ [![GitHub stars](https://img.shields.io/github/stars/b1411/parallel.js.svg?style=social)](https://github.com/b1411/parallel.js)
11
+
12
+ > **Other languages:** [Русский](./README.ru.md)
13
+
14
+ A library for parallel execution of JavaScript/TypeScript functions using Worker Threads in Node.js.
15
+
16
+ ## Performance
17
+
18
+ Benchmarks on 4-core CPU:
19
+
20
+ | Task | Sequential | Parallel (4 workers) | Speedup |
21
+ |------|-----------|---------------------|---------|
22
+ | **Fibonacci(35-42) computation** | 5113 ms | 2606 ms | **1.96x** |
23
+ | **Processing 50 items** | 936 ms | 344 ms | **2.72x** |
24
+
25
+ > Performance improvement: up to 63% on CPU-intensive tasks.
26
+
27
+ ## Features
28
+
29
+ - Real speedup on multi-core processors
30
+ - Simple API for parallel task execution
31
+ - Thread pool for efficient resource management
32
+ - Single thread support for one-off tasks
33
+ - Full TypeScript support
34
+ - Automatic recovery of crashed threads
35
+ - Array processing similar to `map()`, but parallel
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ npm install stardust-parallel-js
41
+ # or
42
+ pnpm install stardust-parallel-js
43
+ # or
44
+ yarn add stardust-parallel-js
45
+ ```
46
+
47
+ ## Quick Start
48
+
49
+ Basic usage example:
50
+
51
+ ```typescript
52
+ import { ThreadPool } from 'stardust-parallel-js';
53
+
54
+ const pool = new ThreadPool(4);
55
+
56
+ // Sequential execution
57
+ const results = data.map(item => heavyComputation(item));
58
+
59
+ // Parallel execution
60
+ const results = await pool.map(data, item => heavyComputation(item));
61
+
62
+ await pool.terminate();
63
+ ```
64
+
65
+ ## Usage
66
+
67
+ ### ThreadPool - Thread pool (recommended)
68
+
69
+ Use `ThreadPool` to process multiple tasks with maximum efficiency:
70
+
71
+ ```typescript
72
+ import { ThreadPool } from 'stardust-parallel-js';
73
+
74
+ // Create a pool of 4 threads (matching CPU cores)
75
+ const pool = new ThreadPool(4);
76
+
77
+ // Process array in parallel
78
+ const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
79
+ const squares = await pool.map(numbers, (n: number) => n * n);
80
+ console.log(squares); // [1, 4, 9, 16, 25, 36, 49, 64]
81
+
82
+ // CPU-intensive computations
83
+ const result = await pool.execute(
84
+ (n: number) => {
85
+ let sum = 0;
86
+ for (let i = 0; i < n; i++) {
87
+ sum += Math.sqrt(i);
88
+ }
89
+ return sum;
90
+ },
91
+ [1000000]
92
+ );
93
+
94
+ // Release resources
95
+ await pool.terminate();
96
+ ```
97
+
98
+ ### Thread - Single thread (for simple tasks)
99
+
100
+ Use `Thread` for one-off operations:
101
+
102
+ ```typescript
103
+ import { Thread } from 'stardust-parallel-js';
104
+
105
+ // Start and wait for result
106
+ const thread = new Thread(
107
+ (text: string) => text.toUpperCase(),
108
+ ['hello world']
109
+ );
110
+
111
+ const result = await thread.join();
112
+ console.log(result); // "HELLO WORLD"
113
+
114
+ // Arrow functions work!
115
+ const thread2 = new Thread(x => x * 2, [21]);
116
+ console.log(await thread2.join()); // 42
117
+ ```
118
+
119
+ ## Examples
120
+
121
+ ### Image Processing
122
+
123
+ ```typescript
124
+ import { ThreadPool } from 'stardust-parallel-js';
125
+
126
+ const pool = new ThreadPool(8);
127
+ const images = ['img1.jpg', 'img2.jpg', /* ... */ 'img100.jpg'];
128
+
129
+ // Process 100 images in parallel
130
+ const processed = await pool.map(images, (path: string) => {
131
+ const fs = require('fs');
132
+ const sharp = require('sharp');
133
+ // Complex image processing
134
+ return processImage(path);
135
+ });
136
+
137
+ await pool.terminate();
138
+ ```
139
+
140
+ ### Parsing Large Data
141
+
142
+ ```typescript
143
+ const pool = new ThreadPool(4);
144
+ const chunks = splitDataIntoChunks(bigData, 1000);
145
+
146
+ // Parse each chunk in parallel
147
+ const parsed = await pool.map(chunks, (chunk: any[]) => {
148
+ return chunk.map(item => parseComplexData(item));
149
+ });
150
+
151
+ await pool.terminate();
152
+ ```
153
+
154
+ ### Calculations and Analytics
155
+
156
+ ```typescript
157
+ const pool = new ThreadPool(4);
158
+
159
+ const results = await pool.map([35, 36, 37, 38, 39, 40], n => {
160
+ function fibonacci(num: number): number {
161
+ if (num <= 1) return num;
162
+ return fibonacci(num - 1) + fibonacci(num - 2);
163
+ }
164
+ return fibonacci(n);
165
+ });
166
+
167
+ await pool.terminate();
168
+ ```
169
+
170
+ ## Benchmarks
171
+
172
+ Run benchmarks:
173
+
174
+ ```bash
175
+ npm run build
176
+ npx tsx benchmarks/cpu-intensive.ts
177
+ npx tsx benchmarks/data-processing.ts
178
+ ```
179
+
180
+ ## API Reference
181
+
182
+ ### ThreadPool
183
+
184
+ #### `constructor(size: number)`
185
+ Creates a thread pool of the specified size.
186
+
187
+ ```typescript
188
+ const pool = new ThreadPool(4);
189
+ ```
190
+
191
+ #### `execute<TArgs, TResult>(fn: (...args: TArgs) => TResult, args?: TArgs): Promise<TResult>`
192
+ Executes a function in an available thread from the pool.
193
+
194
+ ```typescript
195
+ const result = await pool.execute((x: number) => x * x, [5]);
196
+ ```
197
+
198
+ #### `map<T, R>(items: T[], fn: (item: T) => R): Promise<R[]>`
199
+ Applies a function to each array element in parallel.
200
+
201
+ ```typescript
202
+ // Arrow function
203
+ const results = await pool.map([1, 2, 3], n => n * 2);
204
+
205
+ // Regular function
206
+ const results2 = await pool.map([1, 2, 3], function(n) { return n * 2; });
207
+ ```
208
+
209
+ #### `terminate(): Promise<void>`
210
+ Stops all threads and releases resources.
211
+
212
+ ```typescript
213
+ await pool.terminate();
214
+ ```
215
+
216
+ ### Thread
217
+
218
+ #### `constructor<T, TArgs>(fn: (...args: TArgs) => T, args?: TArgs)`
219
+ Creates a new thread to execute a function.
220
+
221
+ ```typescript
222
+ const thread = new Thread((x: number) => x * x, [5]);
223
+ ```
224
+
225
+ #### `join(): Promise<T>`
226
+ Waits for execution to complete and returns the result. Automatically terminates the thread.
227
+
228
+ ```typescript
229
+ const result = await thread.join();
230
+ ```
231
+
232
+ ## Important Notes
233
+
234
+ - Functions execute in an isolated context (separate Worker Thread)
235
+ - Arguments and results must be serializable
236
+ - Closures don't work - functions have no access to external variables
237
+ - Regular and arrow functions are supported
238
+ - `require()` is available inside functions for using Node.js modules
239
+ - Best suited for CPU-intensive tasks (calculations, data processing)
240
+ - For I/O operations (reading files, network) use async/await instead of threads
241
+
242
+ ## When to Use
243
+
244
+ **Use stardust-parallel-js when:**
245
+ - Processing large data arrays
246
+ - Performing complex calculations
247
+ - Parsing or transforming data
248
+ - Processing images/video
249
+ - Need to utilize all CPU cores
250
+
251
+ **Don't use when:**
252
+ - Simple operations (faster to execute sequentially)
253
+ - I/O operations (files, network, DB) - they're already asynchronous
254
+ - Working with DOM (Node.js only)
255
+
256
+ ## Choosing Pool Size
257
+
258
+ ```typescript
259
+ import os from 'os';
260
+
261
+ // Optimal: number of CPU cores
262
+ const pool = new ThreadPool(os.cpus().length);
263
+
264
+ // For CPU-intensive tasks
265
+ const pool = new ThreadPool(os.cpus().length - 1); // leave 1 core for system
266
+
267
+ // For mixed workload
268
+ const pool = new ThreadPool(os.cpus().length * 2);
269
+ ```
270
+
271
+ ## Comparison with Alternatives
272
+
273
+ | Solution | Simplicity | Performance | TypeScript | Size |
274
+ |----------|-----------|-------------|------------|------|
275
+ | **stardust-parallel-js** | High | High | Full | 9.3kB |
276
+ | worker_threads | Medium | High | Partial | Built-in |
277
+ | cluster | Medium | Medium | Partial | Built-in |
278
+ | child_process | Low | Low | No | Built-in |
279
+
280
+ ## Roadmap
281
+
282
+ - [x] Support for transferable objects for large data
283
+ - [ ] Automatic selection of optimal pool size
284
+ - [ ] Task prioritization
285
+ - [ ] Monitoring and statistics
286
+ - [ ] Support for async functions in threads
287
+
288
+ ## Feedback
289
+
290
+ Found a bug or have an idea? [Create an issue](https://github.com/b1411/parallel.js).
291
+
292
+ ## Requirements
293
+
294
+ - Node.js >= 14.0.0 (with Worker Threads support)
295
+
296
+ ## License
297
+
298
+ MIT Β© [b1411](https://github.com/b1411)
299
+
300
+ ---
301
+
302
+ <p align="center">
303
+ Made with ❀️ for the Node.js community
304
+ </p>
305
+
306
+