insomnia/packages/insomnia-app/app/sync/lib/deterministicStringify.ts
Dimitri Mitropoulos 5f4c19da35
[TypeScript] Phase 1 & 2 (#3370)
Co-authored-by: Opender Singh <opender.singh@konghq.com>
2021-05-12 18:35:00 +12:00

35 lines
823 B
TypeScript

export function deterministicStringify(value: any) {
const t = Object.prototype.toString.call(value);
if (t === '[object Object]') {
const pairs: Array<string> = [];
for (const key of Object.keys(value).sort()) {
const k = deterministicStringify(key);
const v = deterministicStringify(value[key]);
if (v !== '' && k !== '') {
pairs.push(`${k}:${v}`);
}
}
return `{${pairs.join(',')}}`;
} else if (t === '[object Array]') {
const items: Array<string> = [];
for (const v of value) {
const vStr = deterministicStringify(v);
if (vStr !== '') {
items.push(vStr);
}
}
return `[${items.join(',')}]`;
}
const str = JSON.stringify(value);
// Only return valid stringifyable things
return str === undefined ? '' : str;
}