UNPKG

canonify

Version:

**NOTE: This is effictively a fork of [@truestamp/canonify](https://www.npmjs.com/package/@truestamp/canonify) to fix an issue with exporting types. Since a repo could not be found, a fork/PR was not possible. All copyrights/attribution has been left in p

36 lines (35 loc) 1.19 kB
// src/index.ts function hasComma(num) { return num === 0 ? "" : ","; } function canonify(object) { if (object === null || typeof object === "undefined" || typeof object === "boolean" || typeof object === "number" || typeof object === "string") { return JSON.stringify(object); } if (typeof object === "bigint") { throw new TypeError("BigInt value can't be serialized in JSON"); } if (typeof object === "function" || typeof object === "symbol") { return canonify(void 0); } if (object.toJSON instanceof Function) { return canonify(object.toJSON()); } if (Array.isArray(object)) { const values2 = object.reduce((t, cv, ci) => { const value = cv === void 0 || typeof cv === "symbol" || typeof cv === "function" ? null : cv; return `${t}${hasComma(ci)}${canonify(value)}`; }, ""); return `[${values2}]`; } const values = Object.keys(object).sort().reduce((t, cv) => { if (object[cv] === void 0 || typeof object[cv] === "symbol" || typeof object[cv] === "function") { return t; } return `${t}${hasComma(t.length)}${canonify(cv)}:${canonify(object[cv])}`; }, ""); return `{${values}}`; } export { canonify };