UNPKG

@gent-js/gent

Version:

template-based data generator.

52 lines (51 loc) 1.73 kB
import { isReadonlyArray } from "../common/utils.js"; import { AbstractJsonable } from "./abstractJsonable.js"; export function stringifyJsonable(value, keyOrIndex, context) { const jsonValue = transformJsonableIntoJsonValue(value, keyOrIndex, context); if (jsonValue === undefined) { return ""; } let jsonString; try { jsonString = JSON.stringify(jsonValue); } catch (error) { console.error(error); jsonString = undefined; } return jsonString; } export function transformJsonableIntoJsonValue(value, keyOrIndex, context) { if (value instanceof AbstractJsonable) { return value.toJSON(keyOrIndex, context); } else if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") { return value; } else if (isReadonlyArray(value)) { return value .map((item) => transformJsonableIntoJsonValue(item, keyOrIndex, context)) .filter((jsonValue) => jsonValue !== undefined); } else { return transformJsonableObjectIntoJsonObject(value, keyOrIndex, context); } } export function transformJsonableObjectIntoJsonObject(jsonableObject, keyOrIndex, context) { let jsonObject = {}; Object.keys(jsonableObject).forEach((memberKey) => { const memberValue = jsonableObject[memberKey]; if (memberValue === undefined) { return; } const memberJsonValue = transformJsonableIntoJsonValue(memberValue, memberKey, context); if (memberJsonValue === undefined) { return; } jsonObject[memberKey] = memberJsonValue; }); return jsonObject; }