/
index.ts
557 lines (510 loc) · 14.2 KB
/
index.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import { Parser } from './parser'
import { isStr, isArr, isFn, isEqual, isObj, isNum, isRegExp } from './shared'
import {
getDestructor,
getInByDestructor,
setInByDestructor,
deleteInByDestructor,
existInByDestructor,
} from './destructor'
import { Segments, Node, Pattern } from './types'
import { Matcher } from './matcher'
const pathCache = new Map()
const isMatcher = Symbol('PATH_MATCHER')
const isValid = (val: any) => val !== undefined && val !== null
const isNumberIndex = (val: any) =>
isStr(val) ? /^\d+$/.test(val) : isNum(val)
const getIn = (segments: Segments, source: any) => {
for (let i = 0; i < segments.length; i++) {
const index = segments[i]
const rules = getDestructor(index as string)
if (!rules) {
if (!isValid(source)) {
if (i !== segments.length - 1) {
return source
}
break
}
source = source[index]
} else {
source = getInByDestructor(source, rules, { setIn, getIn })
break
}
}
return source
}
const setIn = (segments: Segments, source: any, value: any) => {
for (let i = 0; i < segments.length; i++) {
const index = segments[i]
const rules = getDestructor(index as string)
if (!rules) {
if (!isValid(source)) return
if (isArr(source) && !isNumberIndex(index)) {
return
}
if (!isValid(source[index])) {
if (value === undefined) {
return
}
if (i < segments.length - 1) {
source[index] = isNum(segments[i + 1]) ? [] : {}
}
}
if (i === segments.length - 1) {
source[index] = value
}
source = source[index]
} else {
setInByDestructor(source, rules, value, { setIn, getIn })
break
}
}
}
const deleteIn = (segments: Segments, source: any) => {
for (let i = 0; i < segments.length; i++) {
const index = segments[i]
const rules = getDestructor(index as string)
if (!rules) {
if (i === segments.length - 1 && isValid(source)) {
delete source[index]
return
}
if (!isValid(source)) return
source = source[index]
if (!isObj(source)) {
return
}
} else {
deleteInByDestructor(source, rules, {
setIn,
getIn,
deleteIn,
})
break
}
}
}
const hasOwnProperty = Object.prototype.hasOwnProperty
const existIn = (segments: Segments, source: any, start: number | Path) => {
if (start instanceof Path) {
start = start.length
}
for (let i = start; i < segments.length; i++) {
const index = segments[i]
const rules = getDestructor(index as string)
if (!rules) {
if (i === segments.length - 1) {
return hasOwnProperty.call(source, index)
}
if (!isValid(source)) return false
source = source[index]
if (!isObj(source)) {
return false
}
} else {
return existInByDestructor(source, rules, start, {
setIn,
getIn,
deleteIn,
existIn,
})
}
}
}
const parse = (pattern: Pattern, base?: Pattern) => {
if (pattern instanceof Path) {
return {
entire: pattern.entire,
segments: pattern.segments.slice(),
isRegExp: false,
isWildMatchPattern: pattern.isWildMatchPattern,
isMatchPattern: pattern.isMatchPattern,
haveExcludePattern: pattern.haveExcludePattern,
tree: pattern.tree,
}
} else if (isStr(pattern)) {
if (!pattern)
return {
entire: '',
segments: [],
isRegExp: false,
isWildMatchPattern: false,
haveExcludePattern: false,
isMatchPattern: false,
}
const parser = new Parser(pattern, Path.parse(base))
const tree = parser.parse()
if (!parser.isMatchPattern) {
const segments = parser.data.segments
return {
entire: segments.join('.'),
segments,
tree,
isRegExp: false,
isWildMatchPattern: false,
haveExcludePattern: false,
isMatchPattern: false,
}
} else {
return {
entire: pattern,
segments: [],
isRegExp: false,
isWildMatchPattern: parser.isWildMatchPattern,
haveExcludePattern: parser.haveExcludePattern,
isMatchPattern: true,
tree,
}
}
} else if (isFn(pattern) && pattern[isMatcher]) {
return parse(pattern['path'])
} else if (isArr(pattern)) {
return {
entire: pattern.join('.'),
segments: pattern.reduce((buf, key) => {
return buf.concat(parseString(key))
}, []),
isRegExp: false,
isWildMatchPattern: false,
haveExcludePattern: false,
isMatchPattern: false,
}
} else if (isRegExp(pattern)) {
return {
entire: pattern,
segments: [],
isRegExp: true,
isWildMatchPattern: false,
haveExcludePattern: false,
isMatchPattern: true,
}
} else {
return {
entire: '',
isRegExp: false,
segments: pattern !== undefined ? [pattern] : [],
isWildMatchPattern: false,
haveExcludePattern: false,
isMatchPattern: false,
}
}
}
const parseString = (source: any) => {
if (isStr(source)) {
source = source.replace(/\s*/g, '')
try {
const { segments, isMatchPattern } = parse(source)
return !isMatchPattern ? segments : source
} catch (e) {
return source
}
} else if (source instanceof Path) {
return source.segments
}
return source
}
export class Path {
public entire: string | RegExp
public segments: Segments
public isMatchPattern: boolean
public isWildMatchPattern: boolean
public isRegExp: boolean
public haveExcludePattern: boolean
public matchScore: number
public tree: Node
private matchCache: any
private includesCache: any
constructor(input: Pattern, base?: Pattern) {
const {
tree,
segments,
entire,
isRegExp,
isMatchPattern,
isWildMatchPattern,
haveExcludePattern,
} = parse(input, base)
this.entire = entire
this.segments = segments
this.isMatchPattern = isMatchPattern
this.isWildMatchPattern = isWildMatchPattern
this.isRegExp = isRegExp
this.haveExcludePattern = haveExcludePattern
this.tree = tree as Node
this.matchCache = new Map()
this.includesCache = new Map()
}
toString() {
return this.entire?.toString()
}
toArr() {
return this.segments?.slice()
}
get length() {
return this.segments.length
}
concat = (...args: Pattern[]) => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be concat`)
}
const path = new Path('')
path.segments = this.segments.concat(...args.map((s) => parseString(s)))
path.entire = path.segments.join('.')
return path
}
slice = (start?: number, end?: number) => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be slice`)
}
const path = new Path('')
path.segments = this.segments.slice(start, end)
path.entire = path.segments.join('.')
return path
}
push = (...items: Pattern[]) => {
return this.concat(...items)
}
pop = () => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be pop`)
}
return new Path(this.segments.slice(0, this.segments.length - 1))
}
splice = (
start: number,
deleteCount?: number,
...items: Array<string | number>
) => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be splice`)
}
items = items.reduce((buf, item) => buf.concat(parseString(item)), [])
const segments_ = this.segments.slice()
segments_.splice(start, deleteCount, ...items)
return new Path(segments_)
}
forEach = (callback: (key: string | number) => any) => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be each`)
}
this.segments.forEach(callback)
}
map = (callback: (key: string | number) => any) => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be map`)
}
return this.segments.map(callback)
}
reduce = <T>(
callback: (buf: T, item: string | number, index: number) => T,
initial: T
): T => {
if (this.isMatchPattern || this.isRegExp) {
throw new Error(`${this.entire} cannot be reduce`)
}
return this.segments.reduce(callback, initial)
}
parent = () => {
return this.slice(0, this.length - 1)
}
includes = (pattern: Pattern) => {
const { entire, segments, isMatchPattern } = Path.parse(pattern)
const cache = this.includesCache.get(entire)
if (cache !== undefined) return cache
const cacheWith = (value: boolean): boolean => {
this.includesCache.set(entire, value)
return value
}
if (this.isMatchPattern) {
if (!isMatchPattern) {
return cacheWith(this.match(segments))
} else {
throw new Error(`${this.entire} cannot be used to match ${entire}`)
}
}
if (isMatchPattern) {
throw new Error(`${this.entire} cannot be used to match ${entire}`)
}
if (segments.length > this.segments.length) return cacheWith(false)
for (let i = 0; i < segments.length; i++) {
if (!isEqual(String(segments[i]), String(this.segments[i]))) {
return cacheWith(false)
}
}
return cacheWith(true)
}
transform = <T>(
regexp: string | RegExp,
callback: (...args: string[]) => T
): T | string => {
if (!isFn(callback)) return ''
if (this.isMatchPattern) {
throw new Error(`${this.entire} cannot be transformed`)
}
const args = this.segments.reduce((buf, key) => {
return new RegExp(regexp).test(key as string) ? buf.concat(key) : buf
}, [])
return callback(...args)
}
match = (pattern: Pattern): boolean => {
const path = Path.parse(pattern)
const cache = this.matchCache.get(path.entire)
if (cache !== undefined) {
if (cache.record && cache.record.score !== undefined) {
this.matchScore = cache.record.score
}
return cache.matched
}
const cacheWith = (value: any) => {
this.matchCache.set(path.entire, value)
return value
}
if (path.isMatchPattern) {
if (this.isMatchPattern) {
throw new Error(`${path.entire} cannot match ${this.entire}`)
} else {
this.matchScore = 0
return cacheWith(path.match(this.segments))
}
} else {
if (this.isMatchPattern) {
if (this.isRegExp) {
try {
return this['entire']?.['test']?.(path.entire)
} finally {
;(this.entire as RegExp).lastIndex = 0
}
}
const record = {
score: 0,
}
const result = cacheWith(
new Matcher(this.tree, record).match(path.segments)
)
this.matchScore = record.score
return result.matched
} else {
const record = {
score: 0,
}
const result = cacheWith(
Matcher.matchSegments(this.segments, path.segments, record)
)
this.matchScore = record.score
return result.matched
}
}
}
//别名组匹配
matchAliasGroup = (name: Pattern, alias: Pattern) => {
const namePath = Path.parse(name)
const aliasPath = Path.parse(alias)
const nameMatched = this.match(namePath)
const nameMatchedScore = this.matchScore
const aliasMatched = this.match(aliasPath)
const aliasMatchedScore = this.matchScore
if (this.haveExcludePattern) {
if (nameMatchedScore >= aliasMatchedScore) {
return nameMatched
} else {
return aliasMatched
}
} else {
return nameMatched || aliasMatched
}
}
existIn = (source?: any, start: number | Path = 0) => {
return existIn(this.segments, source, start)
}
getIn = (source?: any) => {
return getIn(this.segments, source)
}
setIn = (source?: any, value?: any) => {
setIn(this.segments, source, value)
return source
}
deleteIn = (source?: any) => {
deleteIn(this.segments, source)
return source
}
ensureIn = (source?: any, defaults?: any) => {
const results = this.getIn(source)
if (results === undefined) {
this.setIn(source, defaults)
return this.getIn(source)
}
return results
}
static match(pattern: Pattern) {
const path = Path.parse(pattern)
const matcher = (target) => {
return path.match(target)
}
matcher[isMatcher] = true
matcher.path = path
return matcher
}
static isPathPattern(target: any): target is Pattern {
if (
isStr(target) ||
isArr(target) ||
isRegExp(target) ||
(isFn(target) && target[isMatcher])
) {
return true
}
return false
}
static transform<T>(
pattern: Pattern,
regexp: string | RegExp,
callback: (...args: string[]) => T
): any {
return Path.parse(pattern).transform(regexp, callback)
}
static parse(path: Pattern = '', base?: Pattern): Path {
if (path instanceof Path) {
const found = pathCache.get(path.entire)
if (found) {
return found
} else {
pathCache.set(path.entire, path)
return path
}
} else if (path && path[isMatcher]) {
return Path.parse(path['path'])
} else {
const key_ = base ? Path.parse(base) : ''
const key = `${path}:${key_}`
const found = pathCache.get(key)
if (found) {
return found
} else {
path = new Path(path, base)
pathCache.set(key, path)
return path
}
}
}
static getIn = (source: any, pattern: Pattern) => {
const path = Path.parse(pattern)
return path.getIn(source)
}
static setIn = (source: any, pattern: Pattern, value: any) => {
const path = Path.parse(pattern)
return path.setIn(source, value)
}
static deleteIn = (source: any, pattern: Pattern) => {
const path = Path.parse(pattern)
return path.deleteIn(source)
}
static existIn = (source: any, pattern: Pattern, start?: number | Path) => {
const path = Path.parse(pattern)
return path.existIn(source, start)
}
static ensureIn = (source: any, pattern: Pattern, defaultValue?: any) => {
const path = Path.parse(pattern)
return path.ensureIn(source, defaultValue)
}
}
export { Pattern }