-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathgex.ts
127 lines (104 loc) · 2.76 KB
/
gex.ts
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* Copyright (c) 2011-2020 Richard Rodger, MIT License */
class Gexer {
gexmap: { [key: string]: RegExp }
desc: string = ''
constructor(gexspec: string | string[]) {
this.gexmap = {}
if (null != gexspec) {
let gexstrs = Array.isArray(gexspec) ? gexspec : [gexspec]
gexstrs.forEach((str) => {
this.gexmap[str] = this.re(this.clean(str))
})
}
}
dodgy(obj: any) {
return null == obj || Number.isNaN(obj)
}
clean(gexexp: any) {
let gexstr = '' + gexexp
return this.dodgy(gexexp) ? '' : gexstr
}
match(str: any) {
str = '' + str
let hasmatch = false
let gexstrs = Object.keys(this.gexmap)
for (let i = 0; i < gexstrs.length && !hasmatch; i++) {
hasmatch = !!this.gexmap[gexstrs[i]].exec(str)
}
return hasmatch
}
on(obj: any) {
if (null == obj) {
return null
}
let typeof_obj = typeof obj
if (
'string' === typeof_obj ||
'number' === typeof_obj ||
'boolean' === typeof_obj ||
obj instanceof Date ||
obj instanceof RegExp
) {
return this.match(obj) ? obj : null
} else if (Array.isArray(obj)) {
let out = []
for (let i = 0; i < obj.length; i++) {
if (!this.dodgy(obj[i]) && this.match(obj[i])) {
out.push(obj[i])
}
}
return out
} else {
let outobj: any = {}
for (let p in obj) {
if (Object.prototype.hasOwnProperty.call(obj, p)) {
if (this.match(p)) {
outobj[p] = obj[p]
}
}
}
return outobj
}
}
esc(gexexp: any) {
let gexstr = this.clean(gexexp)
gexstr = gexstr.replace(/\*/g, '**')
gexstr = gexstr.replace(/\?/g, '*?')
return gexstr
}
escregexp(restr: string) {
return restr ? ('' + restr).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') : ''
}
re(gs: string): RegExp | any {
if ('' === gs || gs) {
gs = this.escregexp(gs)
// use [\s\S] instead of . to match newlines
gs = gs.replace(/\\\*/g, '[\\s\\S]*')
gs = gs.replace(/\\\?/g, '[\\s\\S]')
// escapes ** and *?
gs = gs.replace(/\[\\s\\S\]\*\[\\s\\S\]\*/g, '\\*')
gs = gs.replace(/\[\\s\\S\]\*\[\\s\\S\]/g, '\\?')
gs = '^' + gs + '$'
return new RegExp(gs)
} else {
let gexstrs = Object.keys(this.gexmap)
return 1 == gexstrs.length ? this.gexmap[gexstrs[0]] : { ...this.gexmap }
}
}
toString() {
let d = this.desc
return '' != d ? d : (this.desc = 'Gex[' + Object.keys(this.gexmap) + ']')
}
inspect() {
return this.toString()
}
}
function Gex(gexspec: string | string[]): Gexer {
return new Gexer(gexspec)
}
if ('undefined' !== typeof module) {
module.exports = Gex
module.exports.Gex = Gex
}
export default Gex
export { Gex }