-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathargs.js
74 lines (57 loc) · 1.39 KB
/
args.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
var util = require('util');
// In the spirit of scala options
function Arguments() {
var r = process.argv;
var numArgs = r.length;
var args = {};
r.forEach(function (val, index, array) {
if (index < 2) return;
var key;
key = index;
args[index] = val;
});
this.args = args;
this.fn = {};
}
Arguments.prototype.throwMeMaybe = function(obj) {
if (util.isError(obj)) {
obj.type = 'ArgumentsError';
throw obj;
}
return obj;
}
Arguments.prototype.getArgument = function(key, fallback) {
if (this.fn.hasOwnProperty(key)) {
var value = this.fn[key](key, fallback);
if (value === undefined) {
return this.throwMeMaybe(fallback);
}
return value;
}
else if (this.args.hasOwnProperty(key)) {
return this.args[key];
} else {
// Check if fallback is an error. If so, throw it.
return this.throwMeMaybe(fallback);
}
};
Arguments.prototype.last = function() {
var keys = Object.keys(this.args);
var lastKey = keys.reverse()[0];
var last = this.args[lastKey];
return last;
}
Arguments.prototype.penultimate = function() {
var keys = Object.keys(this.args);
var key = keys.reverse()[1];
if (key == undefined) return undefined;
var arg = this.args[key];
return arg;
}
Arguments.prototype.extend = function(key, cb) {
this.fn[key] = cb.bind(this);
}
Arguments.prototype.isSet = function(key) {
return this.args.hasOwnProperty(key);
};
module.exports = new Arguments;