-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathURLBuilder.js
35 lines (35 loc) · 1 KB
/
URLBuilder.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
export class URLBuilder {
pattern;
#tokens = [];
get tokens() {
return this.#tokens;
}
constructor(pattern) {
this.pattern = pattern;
let result;
let i = 0;
const positions = this.#tokens;
while ((result = reg.exec(pattern)) !== null) {
const beforeToken = pattern.substring(i, result.index);
const r = result[0];
const tokenKey = r.substring(1);
i = result.index + r.length;
positions.push([beforeToken, tokenKey]);
}
if (i < pattern.length) {
positions.push([pattern.substring(i), undefined]);
}
}
build(obj) {
const tokens = [];
for (const tokenItem of this.#tokens) {
const [beforeToken, key] = tokenItem;
tokens.push(beforeToken);
if (key !== undefined && key in obj) {
tokens.push(obj[key]);
}
}
return tokens.join('');
}
}
const reg = /\:\w+/g;