-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmodes.js
83 lines (73 loc) · 2.06 KB
/
modes.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
const flagModeChars = [ 'p', 's', 'i', 't', 'n', 'm' ]
const paramModeChars = [ 'l', 'k' ]
const listModeChars = [ 'o', 'v' ]
const isFlagMode = (mode) => flagModeChars.indexOf(mode) !== -1
const isParamMode = (mode) => paramModeChars.indexOf(mode) !== -1
const isListMode = (mode) => listModeChars.indexOf(mode) !== -1
class Modes {
constructor () {
this.flagModes = {}
this.paramModes = {}
this.listModes = {}
}
add (mode, params = []) {
if (isFlagMode(mode)) {
this.flagModes[mode] = true
} else if (isParamMode(mode)) {
this.paramModes[mode] = params[0]
} else if (isListMode(mode)) {
this.listModes[mode] = (this.listModes[mode] || []).concat(params)
}
}
remove (mode, params = []) {
if (isFlagMode(mode)) {
delete this.flagModes[mode]
} else if (isParamMode(mode)) {
delete this.paramModes[mode]
} else if (isListMode(mode)) {
const shouldKeep = (param) => params.every((remove) => param !== remove)
this.listModes[mode] = (this.listModes[mode] || []).filter(shouldKeep)
}
}
get (mode) {
if (isFlagMode(mode)) {
return !!this.flagModes[mode]
} else if (isParamMode(mode)) {
return this.paramModes[mode]
} else if (isListMode(mode)) {
return this.listModes[mode]
}
}
has (mode, param) {
if (isFlagMode(mode)) {
return this.get(mode)
} else if (isParamMode(mode)) {
return this.paramModes[mode] != null
} else if (isListMode(mode) && param) {
const list = this.listModes[mode]
return list && list.indexOf(param) !== -1
}
return false
}
flags () {
return Object.keys(this.flagModes)
}
toString () {
let str = '+' + this.flags().join('')
let params = []
paramModeChars.forEach((mode) => {
if (this.has(mode)) {
str += mode
params.push(this.get(mode))
}
})
if (params.length > 0) {
str += ' ' + params.join(' ')
}
return str
}
}
Modes.isFlagMode = isFlagMode
Modes.isParamMode = isParamMode
Modes.isListMode = isListMode
module.exports = Modes;