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

Commit 8de3990

Browse files
committed
perf(hash.ts): Stop using crypto for bundle size a smaller
1 parent 707bc83 commit 8de3990

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

src/_internal/utils/hash.ts

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,35 @@
11
import { CustomCSSProperties, ClassesObjectType } from '..';
2-
import * as crypto from 'crypto';
32

43
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
54

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;
1010
}
11-
return result;
11+
return Math.abs(hash);
1212
}
1313

14-
function encodeBase36(buffer: Uint8Array): string {
15-
let num = bufferToInteger(buffer);
14+
function encodeBase36(num: number): string {
1615
let result = '';
17-
while (num > 0) {
16+
do {
1817
result = chars[num % 36] + result;
1918
num = Math.floor(num / 36);
20-
}
19+
} while (num > 0);
2120
return result;
2221
}
2322

24-
function getStartingChar(hashBuffer: Uint8Array): string {
23+
function getStartingChar(hash: number): string {
2524
const chars = 'abcdefghijklmnopqrstuvwxyz';
26-
const firstByte = hashBuffer[0];
27-
return chars[firstByte % chars.length];
25+
return chars[hash % chars.length];
2826
}
2927

30-
export function genBase36Hash(object: ClassesObjectType | CustomCSSProperties, n: number) {
28+
export function genBase36Hash(object: ClassesObjectType | CustomCSSProperties, n: number): string {
3129
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);
3533

3634
return startingChar + base36Hash.slice(0, n - 1);
3735
}

0 commit comments

Comments
 (0)