diff --git a/cli/tests/unit/console_test.ts b/cli/tests/unit/console_test.ts index a407df9a12..d7c4fd0cb6 100644 --- a/cli/tests/unit/console_test.ts +++ b/cli/tests/unit/console_test.ts @@ -1466,6 +1466,39 @@ unitTest(function consoleTable(): void { │ 2 │ │ │ 3 │ 6 │ └───────┴───┘ +`, + ); + }); + mockConsole((console, out) => { + console.table([{ a: 0 }, { a: 1, b: 1 }, { a: 2 }, { a: 3, b: 3 }]); + assertEquals( + stripColor(out.toString()), + `┌───────┬───┬───┐ +│ (idx) │ a │ b │ +├───────┼───┼───┤ +│ 0 │ 0 │ │ +│ 1 │ 1 │ 1 │ +│ 2 │ 2 │ │ +│ 3 │ 3 │ 3 │ +└───────┴───┴───┘ +`, + ); + }); + mockConsole((console, out) => { + console.table( + [{ a: 0 }, { a: 1, c: 1 }, { a: 2 }, { a: 3, c: 3 }], + ["a", "b", "c"], + ); + assertEquals( + stripColor(out.toString()), + `┌───────┬───┬───┬───┐ +│ (idx) │ a │ b │ c │ +├───────┼───┼───┼───┤ +│ 0 │ 0 │ │ │ +│ 1 │ 1 │ │ 1 │ +│ 2 │ 2 │ │ │ +│ 3 │ 3 │ │ 3 │ +└───────┴───┴───┴───┘ `, ); }); diff --git a/op_crates/console/02_console.js b/op_crates/console/02_console.js index 587ec0ec2d..e2b95a3904 100644 --- a/op_crates/console/02_console.js +++ b/op_crates/console/02_console.js @@ -1614,20 +1614,12 @@ return this.log(data); } - const objectValues = {}; - const indexKeys = []; - const values = []; - const stringifyValue = (value) => inspectValueWithQuotes(value, new Set(), 0, { ...DEFAULT_INSPECT_OPTIONS, depth: 1, }); const toTable = (header, body) => this.log(cliTable(header, body)); - const createColumn = (value, shift) => [ - ...(shift ? [...new Array(shift)].map(() => "") : []), - stringifyValue(value), - ]; let resultData; const isSet = data instanceof Set; @@ -1649,8 +1641,19 @@ resultData = data; } + const keys = Object.keys(resultData); + const numRows = keys.length; + + const objectValues = properties + ? Object.fromEntries( + properties.map((name) => [name, new Array(numRows).fill("")]), + ) + : {}; + const indexKeys = []; + const values = []; + let hasPrimitives = false; - Object.keys(resultData).forEach((k, idx) => { + keys.forEach((k, idx) => { const value = resultData[k]; const primitive = value === null || (typeof value !== "function" && typeof value !== "object"); @@ -1661,17 +1664,11 @@ const valueObj = value || {}; const keys = properties || Object.keys(valueObj); for (const k of keys) { - if (primitive || !valueObj.hasOwnProperty(k)) { - if (objectValues[k]) { - // fill with blanks for idx to avoid misplacing from later values - objectValues[k].push(""); - } - } else { - if (objectValues[k]) { - objectValues[k].push(stringifyValue(valueObj[k])); - } else { - objectValues[k] = createColumn(valueObj[k], idx); + if (!primitive && k in valueObj) { + if (!(k in objectValues)) { + objectValues[k] = new Array(numRows).fill(""); } + objectValues[k][idx] = stringifyValue(valueObj[k]); } } values.push("");