]> git.r.bdr.sh - rbdr/forum/blob - src/lib/utils/glyph_hash.ts
b70456952184571e472bf529056c698e48df5e6e
[rbdr/forum] / src / lib / utils / glyph_hash.ts
1 export type GlyphHash = GlyphHashFragment[];
2 type GlyphHashFragment = {
3 glyph: string,
4 color: string
5 };
6
7 const internals = {
8 kDehyphenRegex: /[-]/g,
9 kSplitterRegex: /.{1,8}/g,
10 kGlyphs: [
11 '☽',
12 '☆',
13 '♢',
14 '♡',
15 '╱',
16 '╲',
17 '╳',
18 '〰',
19 '▷',
20 '⏊',
21 '〒',
22 '▢',
23 '◯',
24 '⏃',
25 '⏀',
26 '⏆'
27 ],
28 unexpectedUUIDLength: class UnexpectedUUIDLength extends Error {
29 name = 'UnexpectedUUIDLength';
30 message = 'The provided string was not a valid UUIDv4, please provide a 32 character long string'
31 }
32 };
33
34 // Return a glyph with color based on a 4 byte fragment of a UUIDv4
35 const getGlyphHashFragment = function (uuidFragment: string): GlyphHashFragment {
36
37 const glyphIndex = parseInt(uuidFragment.substring(0, 2), 16) % 16;
38 return {
39 glyph: internals.kGlyphs[glyphIndex],
40 color: `#${uuidFragment.substring(2, 8)}`
41 };
42 };
43
44 // Return an array of glyphs based on a UUIDv4
45 export const getGlyphHash = function (uuid: string): GlyphHash {
46
47 const dehyphenedUuid = uuid.replace(/[-]/g, '');
48
49 if (dehyphenedUuid.length !== 32) {
50 throw new internals.unexpectedUUIDLength();
51 }
52
53 const hashFragments = dehyphenedUuid.match(internals.kSplitterRegex);
54 return hashFragments.map(getGlyphHashFragment);
55 };