|
1 | 1 | import { CustomCSSProperties, ClassesObjectType } from '..'; |
2 | | -import * as crypto from 'crypto'; |
3 | 2 |
|
4 | 3 | const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; |
5 | 4 |
|
6 | | -function bufferToInteger(buffer: Uint8Array): number { |
7 | | - let result = 0; |
8 | | - for (let i = 0; i < buffer.length; i++) { |
9 | | - result = result * 256 + buffer[i]; |
| 5 | +function simpleHash(str: string): number { |
| 6 | + let hash = 0; |
| 7 | + for (let i = 0; i < str.length; i++) { |
| 8 | + const char = str.charCodeAt(i); |
| 9 | + hash = (hash << 5) - hash + char; |
10 | 10 | } |
11 | | - return result; |
| 11 | + return Math.abs(hash); |
12 | 12 | } |
13 | 13 |
|
14 | | -function encodeBase36(buffer: Uint8Array): string { |
15 | | - let num = bufferToInteger(buffer); |
| 14 | +function encodeBase36(num: number): string { |
16 | 15 | let result = ''; |
17 | | - while (num > 0) { |
| 16 | + do { |
18 | 17 | result = chars[num % 36] + result; |
19 | 18 | num = Math.floor(num / 36); |
20 | | - } |
| 19 | + } while (num > 0); |
21 | 20 | return result; |
22 | 21 | } |
23 | 22 |
|
24 | | -function getStartingChar(hashBuffer: Uint8Array): string { |
| 23 | +function getStartingChar(hash: number): string { |
25 | 24 | const chars = 'abcdefghijklmnopqrstuvwxyz'; |
26 | | - const firstByte = hashBuffer[0]; |
27 | | - return chars[firstByte % chars.length]; |
| 25 | + return chars[hash % chars.length]; |
28 | 26 | } |
29 | 27 |
|
30 | | -export function genBase36Hash(object: ClassesObjectType | CustomCSSProperties, n: number) { |
| 28 | +export function genBase36Hash(object: ClassesObjectType | CustomCSSProperties, n: number): string { |
31 | 29 | const serialized = JSON.stringify(object); |
32 | | - const hashBuffer = crypto.createHash('sha512').update(serialized).digest(); |
33 | | - const base36Hash = encodeBase36(hashBuffer); |
34 | | - const startingChar = getStartingChar(hashBuffer); |
| 30 | + const hash = simpleHash(serialized); |
| 31 | + const base36Hash = encodeBase36(hash); |
| 32 | + const startingChar = getStartingChar(hash); |
35 | 33 |
|
36 | 34 | return startingChar + base36Hash.slice(0, n - 1); |
37 | 35 | } |
0 commit comments