UNPKG

r3bl-ts-utils

Version:

The `r3bl-ts-utils` package is a set of useful TypeScript functions and classes that can be used in Node.js and browser environments. They are inspired by Kotlin stdlib, and Rust to write code as expressions rather than statements, colorized text, powerfu

83 lines (80 loc) 2.86 kB
"use strict"; /* Copyright 2022 R3BL LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.anyToString = exports.Data = void 0; // Base data class. class Data { toString = () => { const thisAsString = anyToString(this); try { const object = JSON.parse(thisAsString); return JSON.stringify(object, null, 2); } catch (e) { return thisAsString; } }; } exports.Data = Data; function anyToString(arg) { // https://developer.mozilla.org/en-US/docs/Glossary/Primitive if (typeof arg === "function") return ""; else if (typeof arg === "string") return `"${arg}"`; else if (typeof arg === "number") return `${arg}`; else if (typeof arg === "bigint") return `${arg}`; else if (typeof arg === "boolean") return `${arg}`; // else if (typeof arg === "symbol") return `"${String(arg)}"` else if (typeof arg === "undefined") return ""; else if (arg === null) return `null`; // https://2ality.com/2013/10/typeof-null.html const stringArray = new Array(); if (arg instanceof Map) stringArray.push(mapToString(arg)); else if (arg instanceof Set) stringArray.push(arrayToString([...arg])); else if (Array.isArray(arg)) stringArray.push(arrayToString(arg)); else if (typeof arg === "object") stringArray.push(objectToString(arg)); return stringArray.join(", "); } exports.anyToString = anyToString; function mapToString(map) { const strings = new Array(); for (const [key, value] of map.entries()) strings.push(`${anyToString(key)}:${anyToString(value)}`); return `{ ${strings.join(", ")} }`; } function arrayToString(array) { const strings = new Array(); array.forEach((value) => strings.push(`${anyToString(value)}`)); return `[ ${strings.join(", ")} ]`; } function objectToString(object) { const strings = new Array(); for (const [key, value] of Object.entries(object)) { // Skip functions & undefined keys & values. if (typeof value === "function") continue; strings.push(`${anyToString(key)}:${anyToString(value)}`); } return `{ ${strings.join(", ")} }`; } //# sourceMappingURL=data-class.js.map