summaryrefslogtreecommitdiff
path: root/js/src/index.ts
blob: f1b27d3bdbaeba2857410c8cfaecf5558319f124 (plain)
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
import dingbats from "./dingbats";

export interface UnicodeScalarValue {
    codePoint: number;
    string: string;
}

const dingbatsByCodePoint: {[key: string]: UnicodeScalarValue} = {};

const fromCodePoint = String.fromCodePoint ? String.fromCodePoint : fromCodePointPolyfill;

for (const dingbat of dingbats) {
    const codePoint = parseInt(dingbat["Unicode dec"], 10);
    const scalarValue = {
        codePoint: codePoint,
        string: fromCodePoint(codePoint),
    };

    dingbatsByCodePoint[dingbat["Typeface name"] + "_" + dingbat["Dingbat dec"]] = scalarValue;
}

export function codePoint(typeface: string, codePoint: number): UnicodeScalarValue | undefined {
    return dingbatsByCodePoint[typeface + "_" + codePoint];
}

export function dec(typeface: string, dec: string): UnicodeScalarValue | undefined {
    return dingbatsByCodePoint[typeface + "_" + dec];
}

export function hex(typeface: string, hex: string): UnicodeScalarValue | undefined {
    return codePoint(typeface, parseInt(hex, 16));
}

function fromCodePointPolyfill(codePoint: number) {
    if (codePoint <= 0xFFFF) {
        // BMP
        return String.fromCharCode(codePoint);
    } else {
        // Astral
        // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
        const highSurrogate = Math.floor((codePoint - 0x10000) / 0x400) + 0xD800;
        const lowSurrogate = (codePoint - 0x10000) % 0x400 + 0xDC00;
        return String.fromCharCode(highSurrogate, lowSurrogate);
    }
};