const collector = require('./_collector.js');
/**
* @module pete/lib/runs/sync
*/
module.exports = createRunSync;
/**
* This runs target function synchronously.
* Single run is finished as soon as target function returns.
*
* @alias module:pete/lib/runs/sync
* @param {Function} fn to run
* @param {object} options
* @param {any[]} [options.args] to pass to target function
* @param {object} state to modify with `current` and `finished` times
* @return {module:pete/lib/runner~run}
*/
function createRunSync (fn, options, state) {
state.runType = module.filename;
if (!Array.isArray(options.args) || options.args.length < 1) {
return collector(runSyncWithoutArgs.bind(null, fn, state), options, state);
}
return collector(runSyncWithArgs.bind(null, fn, state, options.args), options, state);
}
/**
* @private
* @param {Function} fn to run
* @param {object} state to modify with `current` and `finished` times
* @param {Function} done to call after function returns
*/
function runSyncWithoutArgs (fn, state, done) {
try {
state.current = process.hrtime.bigint();
fn();
state.finished = process.hrtime.bigint();
done();
}
catch (e) {
state.finished = process.hrtime.bigint();
done(e);
}
}
/**
* @private
* @param {Function} fn to run
* @param {object} state to modify with `current` and `finished` times
* @param {any[]} args to pass to target function
* @param {Function} done to call after function returns
*/
function runSyncWithArgs (fn, state, args, done) {
try {
state.current = process.hrtime.bigint();
fn(...args);
state.finished = process.hrtime.bigint();
done();
}
catch (e) {
state.finished = process.hrtime.bigint();
done(e);
}
}