2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-12-01 02:09:06 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts the input into a string. Objects, Sets and Maps are sorted so as to
|
2024-05-15 07:57:20 +00:00
|
|
|
* make tests less flaky.
|
|
|
|
*
|
2023-12-01 02:09:06 +00:00
|
|
|
* @param v Value to be formatted
|
2024-05-15 07:57:20 +00:00
|
|
|
*
|
|
|
|
* @returns The formatted string
|
|
|
|
*
|
|
|
|
* @example Usage
|
|
|
|
* ```ts
|
|
|
|
* import { format } from "@std/internal/format";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2024-05-15 07:57:20 +00:00
|
|
|
*
|
|
|
|
* assertEquals(format({ a: 1, b: 2 }), "{\n a: 1,\n b: 2,\n}");
|
|
|
|
* assertEquals(format(new Set([1, 2])), "Set(2) {\n 1,\n 2,\n}");
|
|
|
|
* assertEquals(format(new Map([[1, 2]])), "Map(1) {\n 1 => 2,\n}");
|
|
|
|
* ```
|
2023-12-01 02:09:06 +00:00
|
|
|
*/
|
|
|
|
export function format(v: unknown): string {
|
|
|
|
// deno-lint-ignore no-explicit-any
|
|
|
|
const { Deno } = globalThis as any;
|
|
|
|
return typeof Deno?.inspect === "function"
|
|
|
|
? Deno.inspect(v, {
|
|
|
|
depth: Infinity,
|
|
|
|
sorted: true,
|
|
|
|
trailingComma: true,
|
|
|
|
compact: false,
|
|
|
|
iterableLimit: Infinity,
|
|
|
|
// getters should be true in assertEquals.
|
|
|
|
getters: true,
|
|
|
|
strAbbreviateSize: Infinity,
|
|
|
|
})
|
|
|
|
: `"${String(v).replace(/(?=["\\])/g, "\\")}"`;
|
|
|
|
}
|