UNPKG

cesr

Version:

[![NPM Version](https://img.shields.io/npm/v/cesr.svg?style=flat)](https://www.npmjs.com/package/cesr) [![NPM License](https://img.shields.io/npm/l/cesr.svg?style=flat)](https://github.com/lenkan/cesr-js/blob/main/LICENSE) [![CI](https://github.com/lenkan

59 lines (58 loc) 2.09 kB
import { concat } from "../array-utils.js"; import { Counter } from "../counter.js"; import { Matter } from "../matter.js"; /** * CESR Generic Map */ export class GenericMapGroup { #map; constructor(init) { this.#map = new Map(Object.entries(init)); } #frames() { const frames = []; for (const [key, value] of this.#map.entries()) { frames.push(Matter.primitive.tag(key)); switch (typeof value) { case "string": frames.push(Matter.primitive.string(value)); break; case "number": frames.push(Matter.primitive.decimal(value)); break; case "boolean": if (value) { frames.push(Matter.from(Matter.Code.Yes, new Uint8Array())); } else { frames.push(Matter.from(Matter.Code.No, new Uint8Array())); } break; case "object": { if (!Array.isArray(value) && value !== null && !(value instanceof Date)) { frames.push(...new GenericMapGroup({ ...value }).#frames()); } else { throw new Error(`Unsupported object type for key ${key}: ${JSON.stringify(value)}`); } break; } default: throw new Error(`Unsupported value type ${typeof value} for key ${key}`); } } const size = frames.reduce((acc, frame) => acc + frame.quadlets, 0); return [Counter.v2.GenericMapGroup(size), ...frames]; } text() { return this.#frames().reduce((acc, frame) => acc + frame.text(), ""); } binary() { return this.#frames().reduce((acc, frame) => { return concat(acc, frame.binary()); }, new Uint8Array()); } static from(init) { return new GenericMapGroup(init); } }