Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
shadowspawn opened this issue Mar 1, 2022 · 1 comment
Closed

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

shadowspawn opened this issue Mar 1, 2022 · 1 comment
Labels
bring-your-own-code Experiments with how authors might build on parseArgs

Comments

@shadowspawn
Copy link
Collaborator

shadowspawn commented Mar 1, 2022

(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 shadowspawn added the bring-your-own-code Experiments with how authors might build on parseArgs label Mar 27, 2022
@shadowspawn
Copy link
Collaborator Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bring-your-own-code Experiments with how authors might build on parseArgs
Projects
None yet
Development

No branches or pull requests

1 participant