Skip to content

Commit

Permalink
Refactor stdio option (#302)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky authored and sindresorhus committed Jun 19, 2019
1 parent a2dc642 commit 977ad1d
Showing 1 changed file with 13 additions and 23 deletions.
36 changes: 13 additions & 23 deletions lib/stdio.js
@@ -1,43 +1,33 @@
'use strict';
const alias = ['stdin', 'stdout', 'stderr'];
const aliases = ['stdin', 'stdout', 'stderr'];

const hasAlias = opts => alias.some(x => Boolean(opts[x]));
const hasAlias = opts => aliases.some(alias => Boolean(opts[alias]));

const stdio = opts => {
if (!opts) {
return;
}

if (opts.stdio && hasAlias(opts)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`);
const {stdio} = opts;

if (stdio === undefined) {
return aliases.map(alias => opts[alias]);
}

if (typeof opts.stdio === 'string') {
return opts.stdio;
if (hasAlias(opts)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
}

const stdio = opts.stdio || [];
if (typeof stdio === 'string') {
return stdio;
}

if (!Array.isArray(stdio)) {
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
}

const result = [];
const len = Math.max(stdio.length, alias.length);

for (let i = 0; i < len; i++) {
let value;

if (stdio[i] !== undefined) {
value = stdio[i];
} else if (opts[alias[i]] !== undefined) {
value = opts[alias[i]];
}

result[i] = value;
}

return result;
const length = Math.max(stdio.length, aliases.length);
return Array.from({length}, (value, index) => stdio[index]);
};

module.exports = stdio;
Expand Down

0 comments on commit 977ad1d

Please sign in to comment.