const { Worker } = require('worker_threads');

 const  runInThread = (fn, ...args) => {
  return new Promise((resolve, reject) => {
    const worker = new Worker(`
      const { parentPort } = require('worker_threads');
      parentPort.on('message', ({fnStr, args}) => {
        const fn = eval('(' + fnStr + ')');
        Promise.resolve(fn(...args))
          .then(result => parentPort.postMessage({result}))
          .catch(err => parentPort.postMessage({error: err.toString()}));
      });
    `, { eval: true });

    worker.on('message', (msg) => {
      if (msg.error) reject(new Error(msg.error));
      else resolve(msg.result);
      worker.terminate();
    });

    worker.on('error', reject);
    worker.postMessage({ fnStr: fn.toString(), args });
  });
}


module.exports = {
    runInThread
} ;


