MCPcopy Create free account
hub / github.com/Effect-TS/effect / format

Function format

packages/effect/src/Formatter.ts:107–185  ·  view source on GitHub ↗
(input: unknown, options?: {
  readonly space?: number | string | undefined
  readonly ignoreToString?: boolean | undefined
})

Source from the content-addressed store, hash-verified

105 * @since 2.0.0
106 */
107export function format(input: unknown, options?: {
108 readonly space?: number | string | undefined
109 readonly ignoreToString?: boolean | undefined
110}): string {
111 const space = options?.space ?? 0
112 const ancestors = new WeakSet<object>()
113 const gap = !space ? "" : (typeof space === "number" ? " ".repeat(space) : space)
114 const ind = (d: number) => gap.repeat(d)
115
116 const wrap = (v: unknown, body: string): string => {
117 const ctor = (v as any)?.constructor
118 return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body
119 }
120
121 const ownKeys = (o: object): Array<PropertyKey> => {
122 try {
123 return Reflect.ownKeys(o)
124 } catch {
125 return ["[ownKeys threw]"]
126 }
127 }
128
129 function recur(v: unknown, d = 0): string {
130 if (typeof v === "string") return JSON.stringify(v)
131
132 if (
133 typeof v === "number" ||
134 v == null ||
135 typeof v === "boolean" ||
136 typeof v === "symbol"
137 ) return String(v)
138
139 if (typeof v === "bigint") return String(v) + "n"
140
141 if (typeof v === "object" || typeof v === "function") {
142 if (ancestors.has(v)) return CIRCULAR
143 ancestors.add(v)
144
145 let output: string
146 if (symbolRedactable in v) {
147 output = recur(getRedacted(v as any), d)
148 } else if (Array.isArray(v)) {
149 output = !gap || v.length <= 1
150 ? `[${v.map((x) => recur(x, d)).join(",")}]`
151 : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`
152 } else if (v instanceof Date) {
153 output = formatDate(v)
154 } else if (
155 !options?.ignoreToString &&
156 Predicate.hasProperty(v, "toString") &&
157 typeof v["toString"] === "function" &&
158 v["toString"] !== Object.prototype.toString &&
159 v["toString"] !== Array.prototype.toString
160 ) {
161 const s = safeToString(v)
162 output = v instanceof Error && v.cause ? `${s} (cause: ${recur(v.cause, d)})` : s
163 } else if (Symbol.iterator in v) {
164 output = `${v.constructor.name}(${recur(Array.from(v as any), d)})`

Callers 2

Formatter.test.tsFile · 0.90
formatJsonFunction · 0.70

Calls 1

recurFunction · 0.70

Tested by

no test coverage detected