-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathurl.js
42 lines (33 loc) · 940 Bytes
/
url.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
const Utf8 = require('./utf8');
module.exports = class Url {
static specialChr = '!*();:@&=+$,/?#[]% ';
static hex = (b) => `%${b < 16 ? '0' : ''}${b.toString(16).toUpperCase()}`;
static encode(raw) {
let out = '';
for (const c of raw) {
const p = c.codePointAt(0);
if (p >= 0x80 || Url.specialChr.includes(c)) {
out += Utf8.unicodeArrToUtf8Arr([p]).map(Url.hex).join('');
continue;
}
out += c;
}
return out;
}
static decode(encoded) {
let out = '';
for (let i = 0; i < encoded.length; ) {
if (encoded[i] === '%') {
const utfBuf = [];
while (i < encoded.length && encoded[i] === '%') {
utfBuf.push(parseInt(encoded.slice(i + 1, i + 3), 16));
i += 3;
}
out += Utf8.unicodeArrToJsStr(Utf8.utf8ArrToUnicodeArr(utfBuf));
continue;
}
out += encoded[i++];
}
return out;
}
};