Last change
on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
713 bytes
|
Line | |
---|
1 | function con(n) {
|
---|
2 | return 0x80 | (n & 0x3f);
|
---|
3 | }
|
---|
4 |
|
---|
5 | export function encode(str) {
|
---|
6 | const arr = str.split("").map(x => x.charCodeAt(0));
|
---|
7 | return _encode(arr);
|
---|
8 | }
|
---|
9 |
|
---|
10 | function _encode(arr) {
|
---|
11 | if (arr.length === 0) {
|
---|
12 | return [];
|
---|
13 | }
|
---|
14 |
|
---|
15 | const [n, ...ns] = arr;
|
---|
16 |
|
---|
17 | if (n < 0) {
|
---|
18 | throw new Error("utf8");
|
---|
19 | }
|
---|
20 |
|
---|
21 | if (n < 0x80) {
|
---|
22 | return [n, ..._encode(ns)];
|
---|
23 | }
|
---|
24 |
|
---|
25 | if (n < 0x800) {
|
---|
26 | return [0xc0 | (n >>> 6), con(n), ..._encode(ns)];
|
---|
27 | }
|
---|
28 |
|
---|
29 | if (n < 0x10000) {
|
---|
30 | return [0xe0 | (n >>> 12), con(n >>> 6), con(n), ..._encode(ns)];
|
---|
31 | }
|
---|
32 |
|
---|
33 | if (n < 0x110000) {
|
---|
34 | return [
|
---|
35 | 0xf0 | (n >>> 18),
|
---|
36 | con(n >>> 12),
|
---|
37 | con(n >>> 6),
|
---|
38 | con(n),
|
---|
39 | ..._encode(ns)
|
---|
40 | ];
|
---|
41 | }
|
---|
42 |
|
---|
43 | throw new Error("utf8");
|
---|
44 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.