microsoft/typespec
Publicmirrored fromhttps://github.com/microsoft/typespecAvailable
packages/html-program-viewer/src/inspect.ts
57lines · modecode
| 1 | const MAX_DEPTH = 2; |
| 2 | |
| 3 | export function inspect(obj: unknown): string { |
| 4 | return formatValue({ depth: 0 }, obj); |
| 5 | } |
| 6 | interface InspectContext { |
| 7 | depth: number; |
| 8 | } |
| 9 | |
| 10 | function formatValue(ctx: InspectContext, obj: unknown) { |
| 11 | switch (typeof obj) { |
| 12 | case "undefined": |
| 13 | return "undefined"; |
| 14 | case "string": |
| 15 | return `"${obj}"`; |
| 16 | case "number": |
| 17 | case "bigint": |
| 18 | case "boolean": |
| 19 | case "symbol": |
| 20 | return obj.toString(); |
| 21 | case "object": |
| 22 | if (obj === null) { |
| 23 | return "null"; |
| 24 | } |
| 25 | return formatObject(ctx, obj); |
| 26 | default: |
| 27 | return "?"; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | function formatObject(ctx: InspectContext, obj: object): string { |
| 32 | if (ctx.depth > MAX_DEPTH) { |
| 33 | return obj.toString(); |
| 34 | } |
| 35 | |
| 36 | if (Array.isArray(obj)) { |
| 37 | return formatArray(ctx, obj); |
| 38 | } |
| 39 | |
| 40 | const props = Object.entries(obj).map(([k, v]) => { |
| 41 | return ` `.repeat(ctx.depth) + `${k}: ${formatValue({ ...ctx, depth: ctx.depth + 1 }, v)}`; |
| 42 | }); |
| 43 | |
| 44 | return ["{", ...props, "}"].join("\n"); |
| 45 | } |
| 46 | |
| 47 | function formatArray(ctx: InspectContext, obj: unknown[]): string { |
| 48 | if (ctx.depth > MAX_DEPTH) { |
| 49 | return obj.toString(); |
| 50 | } |
| 51 | |
| 52 | const items = obj.map((v) => { |
| 53 | return ` `.repeat(ctx.depth) + `${formatValue({ ...ctx, depth: ctx.depth + 1 }, v)}`; |
| 54 | }); |
| 55 | |
| 56 | return ["[", ...items, "]"].join("\n"); |
| 57 | } |
| 58 | |