lib/runs/callback.js

const collector = require('./_collector.js');

/**
 * @module pete/lib/runs/callback
 */
module.exports = createRunCallback;

/**
 * This runs target function by passing a callback to it.
 * Single run is finished after target function calls back.
 *
 * @alias module:pete/lib/runs/callback
 * @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 createRunCallback (fn, options, state) {
	state.runType = module.filename;

	if (!Array.isArray(options.args) || options.args.length < 1) {
		return collector(runCallbackWithoutArgs.bind(null, fn, state), options, state);
	}

	return collector(runCallbackWithArgs.bind(null, fn, state, options.args), options, state);
}

/**
 * @private
 * @param {Function} fn      to run
 * @param {object}   state   to modify with `current` time, just before calling target function
 * @param {Function} done    to call after function returns
 */
function runCallbackWithoutArgs (fn, state, done) {
	state.current = process.hrtime.bigint();
	try {
		fn(done);
	}
	catch (e) {
		done(e);
	}
}

/**
 * @private
 * @param {Function} fn      to run
 * @param {object}   state   to modify with `current` time, just before calling target function
 * @param {any[]}    args    to pass to target function
 * @param {Function} done    to call after function returns
 */
function runCallbackWithArgs (fn, state, args, done) {
	state.current = process.hrtime.bigint();
	try {
		fn(...args, done);
	}
	catch (e) {
		done(e);
	}
}