-
Notifications
You must be signed in to change notification settings - Fork 0
/
numbers.js
103 lines (98 loc) · 2.56 KB
/
numbers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"use strict";
const NixClap = require("..");
/*
* Example to implement a cli program that has these commands:
* sum - add up numbers
* sort - sort numbers
* times - multiply numbers
* divide - divide two numbers
*
* Usage: numbers sum 1 2 3 4
* numbers sort 5 3 3 4 3 1 [--reverse]
* numbers times 3 4 5 6 7
* numbers divide 9 3
*/
//
// exec for command sum
//
const sum = parsed => {
console.log("sum:", parsed.args._.reduce((s, x) => s + x, 0));
};
//
// exec for command sort
//
const sort = parsed => {
console.log("sorted:", parsed.args._.sort((a, b) => (parsed.opts.reverse ? b - a : a - b)));
};
new NixClap({})
.version("1.0.0")
.usage("$0 <command> Num [Num ..]")
.init(
// No top level options
{},
// Commands
{
// command sum
sum: {
alias: "s",
usage: "$0 $1 num [num ..]",
desc: "Output sum of numbers",
// takes a variadic list of numbers into an array named _
args: "<number _..>",
exec: sum
},
// command sort
sort: {
desc: "Output sorted numbers",
alias: "sr",
usage: () => "$0 $1 <num> [num ..]",
// takes a variadic list of numbers into an array named _
args: "<number _..>",
exec: sort,
// options for command sort
options: {
// sort in reverse order
reverse: {
alias: "r",
desc: "Sort in descending order"
}
}
},
// command times
times: {
desc: "Show product of numbers",
alias: ["t", "product", "p"],
usage: "$0 $1 <num> [num ..]",
args: "<number _..>",
exec: parsed => {
console.log("product:", parsed.args._.reduce((p, v) => p * v, 1));
}
},
// command divide
divide: {
desc: "Show result of dividend/divisor",
alias: ["d", "div"],
usage: "$0 $1 <dividend> <divisor>",
args: "<dividend> <divisor>",
exec: parsed => {
let dividend, divisor;
if (parsed.opts.switch) {
dividend = parsed.args.divisor;
divisor = parsed.args.dividend;
} else {
dividend = parsed.args.dividend;
divisor = parsed.args.divisor;
}
const args = parsed.args;
console.log(`quotient of ${dividend}/${divisor}:`, dividend / divisor);
},
options: {
switch: {
alias: "s",
desc: "Switch dividend and divisor"
}
}
}
}
)
.parse();