Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: only use parse and argv at top level (#1990)
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
const argv = require('yargs/yargs')(process.argv.slice(2)).command( | ||
'math', | ||
'math description', | ||
yargs => | ||
yargs | ||
.command( | ||
'add <a> <b>', | ||
'add description', | ||
yargs => | ||
yargs | ||
.positional('a', { | ||
describe: 'addend "a"', | ||
type: 'number', | ||
default: 0, | ||
}) | ||
.positional('b', { | ||
describe: 'addend "b"', | ||
type: 'number', | ||
default: 0, | ||
}), | ||
argv => { | ||
const {a, b} = argv; | ||
console.log(`${a} + ${b} = ${a + b}`); | ||
} | ||
) | ||
.command( | ||
'sum <numbers..>', | ||
'sum description', | ||
yargs => | ||
yargs | ||
.positional('numbers', { | ||
describe: 'numbers to sum', | ||
type: 'array', | ||
default: [], | ||
}) | ||
.check(argv => | ||
isArrayOfNumbers(argv.numbers) | ||
? true | ||
: 'Positional argument "numbers" must only contain numbers' | ||
), | ||
argv => { | ||
const sum = argv.numbers.reduce((a, b) => a + b, 0); | ||
console.log(`The sum of numbers is ${sum}`); | ||
} | ||
) | ||
).argv; | ||
|
||
console.log(argv); | ||
|
||
function isArrayOfNumbers(arr) { | ||
return Array.isArray(arr) && arr.every(n => typeof n === 'number'); | ||
} | ||
|
||
// NOTE: ".argv" and ".parse()" should only be used at top level, not inside builder functions. |