@bitblit/ratchet-common
Version:
Common tools for general use
39 lines • 1.53 kB
JavaScript
import { ErrorRatchet } from './error-ratchet.js';
export class SimpleArgRatchet {
constructor() { }
static parseArgs(args, validArgNames) {
const rval = {};
if (args?.length) {
if (args.length % 2 !== 0) {
throw ErrorRatchet.fErr('Invalid arguments, all args must take the form --a b, but there were an odd number of arguments');
}
for (let i = 0; i < args.length; i += 2) {
let key = args[i];
const value = args[i + 1];
if (!key.startsWith('--')) {
throw ErrorRatchet.fErr('Argument %s does not take the form --x', key);
}
key = key.substring(2);
if (!validArgNames.includes(key)) {
throw ErrorRatchet.fErr('Argument %s is not a valid argument (valid were %j)', key, validArgNames);
}
rval[key] = rval[key] ?? [];
rval[key].push(value);
}
}
return rval;
}
static parseSingleArgs(args, validArgNames) {
const tmp = SimpleArgRatchet.parseArgs(args, validArgNames);
const rval = {};
Object.keys(tmp).forEach((k) => {
const v = tmp[k];
if (v.length > 1) {
throw ErrorRatchet.fErr('Argument %s had %d values, but should have 1', k, v.length);
}
rval[k] = v[0];
});
return rval;
}
}
//# sourceMappingURL=simple-arg-ratchet.js.map