repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

starfx / query
Eric Bower · 18 Jan 24

create-key.ts

 1import { isObject } from "./util.ts";
 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  while (hash.length < len) {
19    hash = "0" + hash;
20  }
21  return hash;
22}
23
24// https://gist.github.com/iperelivskiy/4110988
25const tinySimpleHash = (s: string) => {
26  let h = 9;
27  for (let i = 0; i < s.length;) {
28    h = Math.imul(h ^ s.charCodeAt(i++), 9 ** 9);
29  }
30  return h ^ (h >>> 9);
31};
32
33/**
34 * This function used to set `ctx.key`
35 */
36// deno-lint-ignore no-explicit-any
37export const createKey = (name: string, payload?: any) => {
38  const normJsonString = typeof payload !== "undefined"
39    ? JSON.stringify(deepSortObject(payload))
40    : "";
41  const hash = normJsonString
42    ? padStart(tinySimpleHash(normJsonString).toString(16), 8)
43    : "";
44  return hash ? `${name}|${hash}` : name;
45};