]> git.r.bdr.sh - rbdr/forum/blob - src/lib/utils/glyph_hash.ts
Add svelte check
[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 unexpectedUUIDLength: class UnexpectedUUIDLength extends Error {
12 name = 'UnexpectedUUIDLength';
13 message =
14 'The provided string was not a valid UUIDv4, please provide a 32 character long string';
15 }
16 };
17
18 // Return a glyph with color based on a 4 byte fragment of a UUIDv4
19 const getGlyphHashFragment = function (uuidFragment: string): GlyphHashFragment {
20 const glyphIndex = parseInt(uuidFragment.substring(0, 2), 16) % 16;
21 return {
22 glyph: internals.kGlyphs[glyphIndex],
23 color: `#${uuidFragment.substring(2, 8)}`
24 };
25 };
26
27 // Return an array of glyphs based on a UUIDv4
28 export const getGlyphHash = function (uuid: string): GlyphHash {
29 const dehyphenedUuid = uuid.replace(/[-]/g, '');
30
31 if (dehyphenedUuid.length !== 32) {
32 throw new internals.unexpectedUUIDLength();
33 }
34
35 const hashFragments = dehyphenedUuid.match(internals.kSplitterRegex);
36 return hashFragments.map(getGlyphHashFragment);
37 };