Eric Bower
·
2025-06-06
create-key.ts
1import { isObject } from "./util.js";
2
3// deno-lint-ignore no-explicit-any
4const deepSortObject = (opts?: any) => {
5 if (!isObject(opts)) return opts;
6 return Object.keys(opts)
7 .sort()
8 .reduce<Record<string, unknown>>((res, key) => {
9 res[`${key}`] = opts[key];
10 if (opts[key] && isObject(opts[key])) {
11 res[`${key}`] = deepSortObject(opts[key]);
12 }
13 return res;
14 }, {});
15};
16
17function padStart(hash: string, len: number) {
18 let hsh = hash;
19 while (hsh.length < len) {
20 hsh = `0${hsh}`;
21 }
22 return hsh;
23}
24
25// https://gist.github.com/iperelivskiy/4110988
26const tinySimpleHash = (s: string) => {
27 let h = 9;
28 for (let i = 0; i < s.length; ) {
29 h = Math.imul(h ^ s.charCodeAt(i++), 9 ** 9);
30 }
31 return h ^ (h >>> 9);
32};
33
34/**
35 * This function used to set `ctx.key`
36 */
37// deno-lint-ignore no-explicit-any
38export const createKey = (name: string, payload?: any) => {
39 const normJsonString =
40 typeof payload !== "undefined"
41 ? JSON.stringify(deepSortObject(payload))
42 : "";
43 const hash = normJsonString
44 ? padStart(tinySimpleHash(normJsonString).toString(16), 8)
45 : "";
46 return hash ? `${name}|${hash}` : name;
47};