Skip to content

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

Closed
@shadowspawn

Description

@shadowspawn

(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' ]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bring-your-own-codeExperiments with how authors might build on parseArgs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions