Skip to content

Commit 991a1d9

Browse files
committed
docs(changeset): hash | only create textEncoder when needed
1 parent 9285c47 commit 991a1d9

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

.changeset/swift-kings-float.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"moderndash": patch
3+
---
4+
5+
`hash` | only create textEncoder when needed

benchmark/crypto/hash.bench.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { hash } from 'moderndash';
2+
import { bench, describe } from 'vitest';
3+
4+
import { randomObjectArray } from '../testData.js';
5+
6+
describe('hash', () => {
7+
const objArr = randomObjectArray(20);
8+
9+
bench('moderndash', async () => {
10+
for (const obj of objArr) {
11+
// eslint-disable-next-line no-await-in-loop
12+
await hash(obj);
13+
}
14+
});
15+
});

package/src/crypto/hash.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { Jsonifiable } from '@type/Jsonifiable.js';
22

33
type SupportedAlgorithms = 'SHA-256' | 'SHA-384' | 'SHA-512';
44

5-
const textEncoder = new TextEncoder();
5+
let textEncoder: TextEncoder | undefined;
66

77
/**
88
* Generates a hash from the given data using the specified algorithm.
@@ -28,6 +28,8 @@ const textEncoder = new TextEncoder();
2828
*/
2929

3030
export async function hash(data: Jsonifiable, algorithm: SupportedAlgorithms = 'SHA-256'): Promise<string> {
31+
textEncoder ??= new TextEncoder();
32+
3133
const dataBuffer = typeof data === 'string'
3234
? textEncoder.encode(data)
3335
: textEncoder.encode(JSON.stringify(data));
@@ -36,4 +38,4 @@ export async function hash(data: Jsonifiable, algorithm: SupportedAlgorithms = '
3638
const hashArray = [...new Uint8Array(hashBuffer)];
3739
const hexValues = hashArray.map(b => b.toString(16).padStart(2, '0'));
3840
return hexValues.join('');
39-
}
41+
}

0 commit comments

Comments
 (0)