1
0
silverbullet/plugs/query/util.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-04-29 11:37:31 +00:00
const maxWidth = 70;
// Nicely format an array of JSON objects as a Markdown table
export function jsonToMDTable(
jsonArray: any[],
2022-10-12 09:47:13 +00:00
valueTransformer: (k: string, v: any) => string = (k, v) => "" + v,
): string {
2022-10-14 13:11:33 +00:00
const fieldWidths = new Map<string, number>();
for (let entry of jsonArray) {
for (let k of Object.keys(entry)) {
2022-04-29 11:37:31 +00:00
let fieldWidth = fieldWidths.get(k);
if (!fieldWidth) {
fieldWidth = valueTransformer(k, entry[k]).length;
} else {
fieldWidth = Math.max(valueTransformer(k, entry[k]).length, fieldWidth);
}
fieldWidths.set(k, fieldWidth);
}
}
2022-04-29 11:37:31 +00:00
let fullWidth = 0;
for (let v of fieldWidths.values()) {
fullWidth += v + 1;
}
2022-10-14 13:11:33 +00:00
const headerList = [...fieldWidths.keys()];
const lines = [];
2022-04-29 11:37:31 +00:00
lines.push(
"|" +
headerList
.map(
(headerName) =>
headerName +
2022-10-12 09:47:13 +00:00
charPad(" ", fieldWidths.get(headerName)! - headerName.length),
2022-04-29 11:37:31 +00:00
)
.join("|") +
2022-10-12 09:47:13 +00:00
"|",
2022-04-29 11:37:31 +00:00
);
lines.push(
"|" +
headerList
.map((title) => charPad("-", fieldWidths.get(title)!))
.join("|") +
2022-10-12 09:47:13 +00:00
"|",
2022-04-29 11:37:31 +00:00
);
for (const val of jsonArray) {
let el = [];
for (let prop of headerList) {
2022-04-29 11:37:31 +00:00
let s = valueTransformer(prop, val[prop]);
el.push(s + charPad(" ", fieldWidths.get(prop)! - s.length));
}
lines.push("|" + el.join("|") + "|");
}
return lines.join("\n");
2022-04-29 11:37:31 +00:00
function charPad(ch: string, length: number) {
if (fullWidth > maxWidth && ch === "") {
return "";
} else if (fullWidth > maxWidth && ch === "-") {
return "--";
}
if (length < 1) {
return "";
}
return new Array(length + 1).join(ch);
}
}