Although I've worked with it in C and Java, I forget the basic output method for getting placeholders to make columns on a text output:
Oakenshie开发者_开发知识库ld Thorin
Baggins Bilbo
Gray, the Gandalf
Then, once this function is known, where can I find a standalone library to do it in Javascript?
Do you mean sprintf()
's width format specifier (e.g. %20d
)? If so, Javascript sprintf is indeed your answer.
How I do it
var data = [["Oakenshield", "Thorin"], ["Baggins", "Bilbo"], ["Gray, the", "Gandalf"]];
var display = document.querySelectorAll("[id^=display]");
Library:
var pads = (x,len,z=" ") => (x + Array(len).fill(z).join("")).slice(0,len);
var padn = (x,len,z=0,base) =>
(Array(len).fill(z).join("") + x.toString(base)).slice(-len);
var sprintf = (str, ...argv) => !argv.length ? str :
sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);
Demo1:
var f = item => sprintf("$$\n", pads(item[0],16), pads(item[1],16));
display[0].innerHTML = data.map(f).join("");
Demo2:
var f = (item,i) => sprintf("$ $ $ $\n",
padn(i,4), padn(item[1],6," "), pads(item[0],9), padn(i,4,0,2));
display[1].innerHTML = data.map(f).join("");
<b>Demo 1:</b><pre id="display1" style="margin-top: 0"></pre>
<b>Demo 2:</b><pre id="display2" style="margin-top: 0"></pre>
精彩评论