UNPKG

tiny-types

Version:

A tiny library that brings Tiny Types to JavaScript and TypeScript

65 lines 2.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toJSON = toJSON; const isRecord_1 = require("./isRecord"); /** * Serialises the object to a JSON representation. * * @param value */ function toJSON(value) { switch (true) { case value && !!value.toJSON: return value.toJSON(); case value && Array.isArray(value): return value.map(v => { return v === undefined ? null : toJSON(v); }); case value && value instanceof Map: return mapToJSON(value); case value && value instanceof Set: return toJSON(Array.from(value)); case value && (0, isRecord_1.isRecord)(value): return recordToJSON(value); case value && value instanceof Error: return errorToJSON(value); case isSerialisablePrimitive(value): return value; default: return JSON.stringify(value); } } function mapToJSON(map) { const serialised = Array.from(map, ([key, value]) => [toJSON(key), toJSON(value)]); return Object.fromEntries(serialised); } function recordToJSON(value) { const serialised = Object.entries(value) .map(([k, v]) => [toJSON(k), toJSON(v)]); return Object.fromEntries(serialised); } function errorToJSON(value) { return Object.getOwnPropertyNames(value) .reduce((serialised, key) => { serialised[key] = toJSON(value[key]); return serialised; }, {}); } function isSerialisableNumber(value) { return typeof value === 'number' && !Number.isNaN(value) && value !== Number.NEGATIVE_INFINITY && value !== Number.POSITIVE_INFINITY; } function isSerialisablePrimitive(value) { if (['string', 'boolean'].includes(typeof value)) { return true; } if (value === null || value === undefined) { return true; } return isSerialisableNumber(value); } //# sourceMappingURL=toJSON.js.map