pkgjs / parseargs

Polyfill of `util.parseArgs()`
Apache License 2.0
121 stars 9 forks source link

How might I add my own support for negative numbers? #72

Closed shadowspawn closed 2 years ago

shadowspawn commented 2 years ago

(This is a bring-your-own-feature experiment, not a prototype of parseArgs implementation.)

Inspired by discussion in #62. How could I add my own support for options and positionals treating negative numbers as ordinary args and not options?

const { parseArgs } = require('@pkgjs/parseArgs');

const kNegativePrefix = 'parseArgs.NEGATIVE:';
// preprocess
const rawArgs = process.argv.slice(2);
const preparedArgs = rawArgs.map(arg => /^-[0-9]+/.test(arg) ? kNegativePrefix.concat(arg) : arg);

const result = parseArgs({ 
  args: preparedArgs, {
  options: { profit: { type: 'string' }}
});

// postprocess
const stripPrefix = (arg) => arg.startsWith(kNegativePrefix) ? arg.slice(kNegativePrefix.length) : arg;
result.positionals = result.positionals.map(arg => stripPrefix(arg));
Object.entries(result.values).forEach(([key, value]) => {
    if (typeof value === 'string')
        result.values[key] = stripPrefix(value);
});

console.log(result);
% node index.js --profit 33 44  
{
  flags: { profit: true },
  values: { profit: '33' },
  positionals: [ '44' ]
}
% node index.js --profit -33 -44
{
  flags: { profit: true },
  values: { profit: '-33' },
  positionals: [ '-44' ]
}
shadowspawn commented 2 years ago

This hasn't attracted any interest, and there hasn't been any further discussions about number processing. Closing as insufficiently interesting. 😴