lib/runs/generator.js

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

/**
 * @module pete/lib/runs/generator
 */
module.exports = createRunGenerator;

/**
 * This runs target generator function synchronously.
 *
 * @alias module:pete/lib/runs/generator
 * @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 createRunGenerator (fn, options, state) {
	state.runType = module.filename;

	const iterator = Array.isArray(options.args) && options.args.length >= 0 ? fn(...options.args) : fn();
	return collector(runGeneratorWithoutArgs.bind(null, iterator.next.bind(iterator), state), 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 runGeneratorWithoutArgs (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);
	}
}