Skip to content

Commit adf838e

Browse files
fix: make format match browser console log
1 parent 989d35c commit adf838e

2 files changed

Lines changed: 10 additions & 8 deletions

File tree

packages/shared/src/format.test.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,16 @@ describe("format", () => {
4747
expect(format(NaN)).toBe("NaN");
4848
});
4949
it("handles Maps", () => {
50-
const map = new Map([
50+
const map = new Map<string|number,string|number>([
5151
["a", 1],
52-
["b", 2],
52+
["b", "2"],
53+
[3, "three"],
5354
]);
54-
expect(format(map)).toBe("Map(2) { 'a' => 1, 'b' => 2 }");
55+
expect(format(map)).toBe("Map(3) {'a' => 1, 'b' => '2', 3 => 'three'}");
5556
});
5657
it("handles Sets", () => {
5758
const set = new Set([1, "2", 3]);
58-
expect(format(set)).toBe("Set(3) { 1, '2', 3 }");
59+
expect(format(set)).toBe("Set(3) {1, '2', 3}");
5960
});
6061
it("handles BigInts", () => {
6162
expect(format(BigInt(10))).toBe("10n");

packages/shared/src/format.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
import { inspect } from "util/util";
22

3-
const quoteString = (x: unknown) => (typeof x === "string" ? `'${x}'` : x);
3+
const quoteString = <T>(x: T): T | string =>
4+
typeof x === "string" ? `'${x}'` : x;
45

56
export function format(x: unknown): string {
67
// We're trying to mimic console.log, so we avoid wrapping strings in quotes:
78
if (typeof x === "string") return x;
89
if (x instanceof Set) {
9-
return `Set(${x.size}) { ${Array.from(x, quoteString).join(", ")} }`;
10+
return `Set(${x.size}) {${Array.from(x, quoteString).join(", ")}}`;
1011
}
1112

1213
if (x instanceof Map) {
1314
return `Map(${x.size}) {${Array.from(
1415
x.entries(),
15-
([k, v]) => ` '${k}' => ${v}`,
16-
).join(",")} }`;
16+
([k, v]) => `${quoteString(k)} => ${quoteString(v)}`,
17+
).join(", ")}}`;
1718
}
1819

1920
if (typeof x === "bigint") {

0 commit comments

Comments
 (0)