Use the performance capabilities of web worker
in the browser to avoid blocking the main thread
npm i shadow-worker #or
npm install shadow-worker --save
import { compute } from 'shadow-worker';
await compute(() => [1, 2, 3, 4].map(x => x * 2));
// [2,4,6,8]
const fn = arr => arr.map(x => x * 2);
await compute(fn, [1, 2, 3, 4]);
// [2,4,6,8]
// # debug options
await compute(fn, [1, 2, 3, 4], { label: 'fn', printScript: true });
// data:text/javascript;charset=UTF-8,onmessage=(()=>({data})=>postMessage((arr => {arr.map(x=>x*2)})(data)))(postMessage);
// fn: 16.487060546875ms
// [2, 4, 6, 8]
import { compute } from 'shadow-worker';
compute(() => [1, 2, 3, 4].map(x => x * 2)).then(console.log);
// [2, 4, 6, 8]
/**
* You can easily use `web worker`.
* Using `web worker` is as easy as using a function, as natural as breathing.
* The function will `dynamically` help you generate functions that communicate with the worker channel
* It will be automatically closed when you are finished, so you don't have to worry about the performance problems.
*
* @template T
* @param {(value?: T) => T} callback Function used for `calculation`
* @param {T} [value] Parameters used for calculation
* @param {debugOptions} [options={}] Debug option label:`string`,printScript:`boolean`
* @returns {(Promise<T> | T)} Calculated result
*/
Note: Just in browser node.js side can't use
- add test case
- spuer node side