Skip to content
This repository was archived by the owner on Jan 30, 2025. It is now read-only.

Commit 7f16a95

Browse files
committed
feat(hash.ts): update hash algorithm
1 parent d191eda commit 7f16a95

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/_internal/utils/hash.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { CustomCSSProperties, ClassesObjectType } from '..';
22
import * as crypto from 'crypto';
33

4-
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
4+
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
55

66
function bufferToInteger(buffer: Uint8Array): number {
77
let result = 0;
@@ -11,20 +11,27 @@ function bufferToInteger(buffer: Uint8Array): number {
1111
return result;
1212
}
1313

14-
function encodeBase62(buffer: Uint8Array): string {
14+
function encodeBase36(buffer: Uint8Array): string {
1515
let num = bufferToInteger(buffer);
1616
let result = '';
1717
while (num > 0) {
18-
result = chars[num % 62] + result;
19-
num = Math.floor(num / 62);
18+
result = chars[num % 36] + result;
19+
num = Math.floor(num / 36);
2020
}
2121
return result;
2222
}
2323

24-
export function genBase62Hash(object: ClassesObjectType | CustomCSSProperties, n: number) {
24+
function getStartingChar(hashBuffer: Uint8Array): string {
25+
const chars = 'abcdefghijklmnopqrstuvwxyz';
26+
const firstByte = hashBuffer[0];
27+
return chars[firstByte % chars.length];
28+
}
29+
30+
export function genBase36Hash(object: ClassesObjectType | CustomCSSProperties, n: number) {
2531
const serialized = JSON.stringify(object);
26-
const hashBuffer = crypto.createHash('sha256').update(serialized).digest();
27-
const base62Hash = encodeBase62(hashBuffer);
32+
const hashBuffer = crypto.createHash('sha512').update(serialized).digest();
33+
const base36Hash = encodeBase36(hashBuffer);
34+
const startingChar = getStartingChar(hashBuffer);
2835

29-
return base62Hash.slice(0, n);
36+
return startingChar + base36Hash.slice(0, n - 1);
3037
}

0 commit comments

Comments
 (0)