-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
90 lines (77 loc) · 2.58 KB
/
index.ts
File metadata and controls
90 lines (77 loc) · 2.58 KB
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
class UnicodeRange {
static REGEXP = /^u\+(?:([0-9a-f]?[0-9a-f?]{1,5})|([0-9a-f]{1,6})-([0-9a-f]{1,6}))?$/i;
static splitRanges(ranges: string | string[]): string[] {
if (typeof ranges === 'string') {
return ranges.replace(/\s*/g, '').split(',');
}
return ranges;
}
static parse(ranges: string[] | string): number[] {
const result = new Set<number>();
const arr = UnicodeRange.splitRanges(ranges);
for (const range of arr) {
if (!UnicodeRange.REGEXP.test(range)) {
throw new TypeError(`"${range}" is invalid unicode-range.`);
}
const [, single, start, end] = range.match(UnicodeRange.REGEXP)!;
// Single unicode-range (e.g. U+20, U+3F U+30??)
if (single) {
if (/\?[^?]+$/.test(single)) {
throw new TypeError(`"${range}" is invalid unicode-range.`);
}
if (single.includes('?')) {
const start = single.replace(/\?/g, '0');
const end = single.replace(/\?/g, 'F');
const tmp = UnicodeRange.parse([`U+${start}-${end}`]);
for (const codePoint of tmp) {
result.add(codePoint);
}
} else {
result.add(parseInt(single, 16));
}
}
// Interval unicode-range (e.g. U+30-39)
if (start && end) {
const startCodePoint = parseInt(start, 16);
const endCodePoint = parseInt(end, 16);
for (let codePoint = startCodePoint; codePoint <= endCodePoint; codePoint++) {
result.add(codePoint);
}
}
}
return Array.from(result).sort((a, b) => a - b);
}
static stringify(arr: number[]): string[] {
const sorted = Array.from(new Set(arr)).sort((a, b) => a - b);
const results: string[] = [];
let rangeStart;
for (let idx = 0; idx < sorted.length; idx++) {
const current = sorted[idx];
const prev = sorted[idx - 1];
if (rangeStart && current - prev !== 1) {
results.push(UnicodeRange.rangeString(rangeStart, prev));
rangeStart = current;
}
// First
if (!rangeStart) {
rangeStart = current;
}
// Last
if (idx === sorted.length - 1) {
if (rangeStart === current) {
results.push(UnicodeRange.rangeString(current));
} else {
results.push(UnicodeRange.rangeString(rangeStart, current));
}
}
}
return results;
}
private static rangeString(start: number, end?: number) {
if (!end || start === end) {
return `U+${start.toString(16)}`;
}
return `U+${start.toString(16)}-${end.toString(16)}`;
}
}
export { UnicodeRange };