-
Notifications
You must be signed in to change notification settings - Fork 0
/
sargs.js
103 lines (93 loc) · 2.04 KB
/
sargs.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
function sargs(args){
if (!(this instanceof sargs)) {
return new sargs(args)
}
var self = this
var lets = this.lets = {}
lets.counts = {}
lets.types = {}
self.args = function args(){
var args = Array.prototype.slice.call(arguments)
var lets = self.lets
var who = self.isWho
var array = []
for (var index = 0; index < args.length; index++) {
var type = who(args[index])
array.push(type.toLowerCase())
}
var result
var handler = lets.types[array.join(' ')] || lets.counts['' + args.length] || lets.handler
if (typeof handler === 'function') {
result = handler.apply(lets.self || this, args)
}
if (lets.result) {
result = lets.result
}
return result
}
self.arguments = function(){
return this.args.apply(this, arguments[0])
}
}
module.exports = sargs
sargs.prototype.self = function(object){
if (object) {
this.lets.self = object
}
return this
}
sargs.prototype.result = function(result){
if (result) {
this.lets.result = result
}
return this
}
sargs.prototype.who = function(handler){
if (typeof handler === 'function') {
this.isWho = handler
}
return this
}
sargs.prototype.isWho = function(arg){
var type = typeof arg
if (type === 'object') {
if (Array.isArray(arg)) {
type = 'array'
} else if (arg === null) {
type = 'null'
} else if (arg instanceof Date) {
type = 'Date'
} else if (arg instanceof RegExp) {
type = 'RegExp'
} else if (arg instanceof Error) {
type = 'Error'
}
} else if (type === 'number') {
if (isNaN(arg)) {
type = 'NaN'
}
}
return type
}
sargs.prototype.handler = function(handler){
if (typeof handler === 'function') {
this.lets.handler = handler
}
return this
}
sargs.prototype.counts = function(count, handler){
if (typeof handler === 'function') {
if (typeof count === 'number') {
this.lets.counts['' + count] = handler
}
}
return this
}
sargs.prototype.types = function(types, handler){
if (typeof handler === 'function') {
if (typeof types === 'string') {
this.lets.types[types.trim().toLowerCase()] = handler
}
}
return this
}