-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash-object.ts
37 lines (33 loc) · 1.07 KB
/
hash-object.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @file hash-object.ts
* @author Brandon Kalinowski
* @description Take a JavaScript object and compute a sha256 hash of it for comparison.
* @copyright 2020-2024 Brandon Kalinowski
* @license MIT
*/
import { sha256 } from "https://deno.land/x/sha256@v1.0.2/mod.ts";
/** A JSON replacer that sorts keys recursively and removes type key when required. */
export const replacer = (_key: any, value: any) => {
if (value instanceof Object && !(value instanceof Array)) {
return Object.keys(value)
.sort()
.reduce((sorted, key) => {
(sorted as any)[key] = value[key];
return sorted;
}, {});
}
return value;
};
/** print deterministic JSON string specifically for karabiner */
export function orderedJSONString(obj: any) {
return JSON.stringify(obj, replacer).trimEnd();
}
/**
* Takes a JavaScript object and computes a sha256 hash of the deterministic JSON string.
* @param obj
*/
// deno-lint-ignore require-await
export async function hashObject(obj: any): Promise<string> {
const str = orderedJSONString(obj);
return sha256(str, "utf8", "hex") as string;
}