/
PathNotation.ts
322 lines (209 loc) · 6.92 KB
/
PathNotation.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
const IS_INDEX_REGEX = /^(0|[1-9][0-9]*)$/;
/**
* A dot-notation based path string which yields key literals, allows
* for the inclusion of the "." character in keys and square bracket notation
* in path strings, promotes readability of path strings and provides other
* useful utilities for reasoning and working with object paths.
*/
export default class PathNotation extends Array<string | number> {
constructor(...path:(string | number | PathNotation)[])
{
super();
const keys:(string | number)[] = [];
for(const constructArg of path) {
switch(typeof constructArg) {
case 'string':
keys.push(...PathNotation.pathNotationToKeys(constructArg));
break;
case 'number':
keys.push(constructArg);
break;
default:
keys.push(...constructArg);
break;
}
}
this.push(...keys);
}
//Accessors
/**
* Root key of path.
*/
get firstKey():string | number {
return this[0];
}
/**
* Terminal key of path.
*/
get lastKey():string | number {
return this[this.length - 1];
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
//Methods
slice(begin?:number, end?:number): PathNotation {
return new PathNotation(...super.slice(begin, end));
}
splice(start?:number, deleteCount?:number, ...items:(string | number)[]):
PathNotation
{
return new PathNotation(...super.splice(start, deleteCount, ...items));
}
toString():string {
return PathNotation.keysToPathNotation(this);
}
/**
* Yields key literals from dot-notated path.
* @note
* When string representing positive integer is in square bracket notation,
* the string is parsed into an integer.
* ```
* const pathKeys = Array.from(PathNotation.pathNotationToKeys("foo[2]"));
* console.log(pathKeys[1] === 2); // true
* ```
* @note
* Characters ".", "\\", and, "[" are escaped with double backslashes outside
* of square bracket notation and the character "]" is escaped with double
* backslashes inside of square bracket notation. In all other cases double
* backslashes are parsed as a single slash in the path. This allows for the
* "\\" character in paths and to pass double backslash escaping to consumers
* of [[PathNotation]].
*/
static *pathNotationToKeys(path:string):IterableIterator<string | number> {
let key = '';
let squareBracket = false;
for(let i = 0, len = path.length; i < len; i++) {
const char = path[i];
// Escape char
if(char === '\\'){
const nextIndex = i + 1;
// Last char ignore
if(nextIndex === len) {
key += char;
continue;
}
const nextChar = path[nextIndex];
// The only escapable chars in square bracket notation is ']'
if(squareBracket) {
if(nextChar === ']') {
// add nextChar and increment i so nextChar is skipped next loop
key += nextChar;
i++;
} else {
key += char;
}
continue;
}
// The only escapable chars outside of square bracket notation are
// '\', '.', and '['
switch(nextChar) {
// add nextChar and increment i so nextChar is skipped next loop
case '.':
case '[':
case '\\':
key += nextChar;
i++;
break;
default:
key += char;
}
// Open square bracket
} else if(char === '[' && squareBracket === false) {
squareBracket = true;
if(key.length > 0) {
yield key;
key = '';
}
// Close square bracket, yield and reset key
} else if(char === ']' && squareBracket) {
squareBracket = false;
if(key.length > 0) {
yield IS_INDEX_REGEX.test(key) ? Number.parseInt(key) : key;
key = '';
}
// Key terminator, yield key and reset
} else if(char === '.' && squareBracket === false) {
if(key.length > 0){
yield key;
key = '';
}
// Add char to key
} else {
key += char;
}
}
//Yield terminal key
if(key.length > 0){
yield key;
}
}
/**
* Returns dot-notated and square bracket notated path string.
* @note
* When a key contains the "." character, the "\\" character, or the key is a
* positive integer, the key is formatted in square bracket notation.
* ```
* // Key with "." character
* let pathStr = PathNotation.keysToPathNotation(['foo', 'bar.baz']);
* console.log(pathStr); // "foo[bar.baz]"
*
* // Key with "\" character
* pathStr = PathNotation.keysToPathNotation(['foo', 'bar\\baz']);
* console.log(pathStr); // "foo[bar\baz]"
*
* // Key that is positive integer
* pathStr = PathNotation.keysToPathNotation(['foo', 2]);
* console.log(pathStr); // "foo[2]"
* ```
* @note
* When a key is formatted with square bracket notation due to a "." or "\\"
* character and it contains a "]" character. The "]" is escaped.
* ```
* const pathStr = PathNotation.keysToPathNotation(['foo', 'bar.baz]qux']);
* console.log(pathStr); // "foo[bar.baz\]qux]"
* ```
*/
static keysToPathNotation(keys:Iterable<string | number>):string
{
const keysIter = keys[Symbol.iterator]();
// Handle first key
let keysIterResult = keysIter.next();
// Empty keys iterable
if(keysIterResult.done){
return '';
}
let pathNotation:string;
let key = keysIterResult.value;
if(typeof key === 'number') {
pathNotation = Number.isInteger(key) && key > -1 ? `[${key}]`
: key.toString();
} else if(key.indexOf('.') > -1 || key.indexOf('\\') > -1) {
// Escape closing square brackets that are apart of path
key = (<string>key).split(']').join('\\]');
pathNotation = `[${key}]`;
} else {
pathNotation = key;
}
// Handle remaining keys
keysIterResult = keysIter.next();
while(!keysIterResult.done) {
key = keysIterResult.value;
if(typeof key === 'number') {
if(Number.isInteger(key) && key > -1) {
pathNotation = `${pathNotation}[${key}]`;
} else {
pathNotation = `${pathNotation}.${key}`;
}
} else if(key.indexOf('.') > -1 || key.indexOf('\\') > -1){
// Escape closing square brackets that are apart of path
key = (<string>key).split(']').join('\\]');
pathNotation = `${pathNotation}[${key}]`;
} else {
pathNotation = `${pathNotation}.${key}`;
}
keysIterResult = keysIter.next();
}
return pathNotation;
}
}