Skip to content

Instantly share code, notes, and snippets.

@bitifet
Created July 14, 2022 11:10
Show Gist options
  • Save bitifet/4da6f29b44db9a9dfa13149c5593d504 to your computer and use it in GitHub Desktop.
Save bitifet/4da6f29b44db9a9dfa13149c5593d504 to your computer and use it in GitHub Desktop.
Log objects aside in console.
function aside(...args) {
// Usage examples:
// ---------------
// console.log(aside(var1, var2));
// console.log(aside({var1, var2, someValue: 23}));
// console.log(aside.bind("My title")(var1, var2));
// console.log(
// aside.bind({
// title: "My title",
// separator: "#",
// ruler: "#",
// maxColumnLength: 30,
// tabSize: 4,
// bottomRuler: false,
// })({a, b, c, d});
// );
// ---------------
let options = this || {};
if (typeof options == "string") options = {title: options};
const prm = {
title: false,
separator: " | ",
ruler: "-",
tabSize: 2,
maxColumnLength: Infinity,
...options
};
if (prm.bottomRuler === undefined) {
// Set it explicitly to false to disable bottom ruler:
prm.bottomRuler = prm.ruler;
};
let labels = "";
if (
args.length == 1
&& typeof args[0] == "object"
) {
labels = Object.keys(args[0]);
args = Object.values(args[0]);
};
args = args.map(a=>(
typeof a != "object" ? String(a)
: JSON.stringify(a, null, prm.tabSize)
));
const rows = args.map(a=>a
.split("\n")
.map(r=>r.substring(0, prm.maxColumnLength))
);
const widths = rows.map(r=>Math.max(...r.map(s=>s.length)))
const maxHeight = Math.max(...rows.map(r=>r.length))
for (let i=0; i<rows.length; i++) {
const rl = rows[i].length;
rows[i].length = maxHeight;
rows[i].fill("", rl, maxHeight);
rows[i] = rows[i].map(s=>s.padEnd(widths[i]));
};
let output = [];
output.length = maxHeight;
output = output.fill("")
.map(
(foo,i)=>rows.map(r=>r[i])
.join(prm.separator)
)
;
if (labels) labels = [
labels
.map((l,i)=>l.padEnd(widths[i]))
.join(prm.separator)
, output[0].replace(/./g, prm.ruler[0]
, ""
].join("\n");
const bottomRuler = (
prm.bottomRuler ? "\n"+ output[0]
.replace(/./g, prm.bottomRuler[0])
: ""
);
const title = (
prm.title ? prm.title + "\n"
: ""
);
return title
+ labels
+ output.join("\n")
+ bottomRuler
;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment