typia
Version:
Superfast runtime validators with only one line
40 lines (39 loc) • 1.78 kB
JavaScript
//#region src/internal/_jsonStringifyArray.ts
/**
* Serializes the elements of an array the way ECMAScript `JSON.stringify` does.
*
* `SerializeJSONArray` walks index `0` to `LengthOfArrayLike(value) - 1` and
* writes `null` wherever the element serializes to `undefined`. Neither
* `Array.prototype.map` nor `Array.prototype.join` reproduces that:
*
* - `map` never visits a hole and leaves one behind, and `join` renders a hole as
* empty text, so a sparse array joined into malformed text such as `[,1]`. A
* hole exists at runtime whatever the element type declares, so this is not
* an `any` concern.
* - `join` renders a mapped `undefined` as empty text too, which is what an `any`
* or `unknown` element holding a function, a symbol, or a `toJSON` that
* returns nothing serializes to.
*
* The length is converted with `ToLength` and read once, which is both what
* `JSON.stringify` does and what `Array.prototype.every` - the traversal
* typia's own array checkers emit - does, so the checker and the serializer
* walk one index range rather than two that merely usually coincide.
*
* @param elements Array being serialized.
* @param mapper Serializer of one element, emitted by the transform.
* @returns Comma separated element text, without the enclosing brackets.
* @internal
*/
const _jsonStringifyArray = (elements, mapper) => {
const length = Math.min(Math.max(Math.trunc(elements.length) || 0, 0), Number.MAX_SAFE_INTEGER);
let output = "";
for (let i = 0; i < length; ++i) {
const elem = elements[i];
const text = elem === void 0 ? void 0 : mapper(elem, i);
output += (i === 0 ? "" : ",") + (text === void 0 ? "null" : text);
}
return output;
};
//#endregion
export { _jsonStringifyArray };
//# sourceMappingURL=_jsonStringifyArray.mjs.map