4

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:

Oakenshield     Thorin
Baggins         Bilbo
Gray, the       Gandalf

Then, once this function is known, where can I find a standalone library to do it in Javascript?

Ben
  • 54,723
  • 49
  • 178
  • 224
  • Do you mean the `\t` character? (tab character?) – Alex Nov 19 '10 at 06:14
  • @Alex - No, I think it's `sprintf` or `printf` or something. If it's `sprintf` then my solution is here: http://stackoverflow.com/questions/610406/javascript-printf-string-format. There's a specific IO way to do it that I can't recall. For example, %20 makes a 20-character column, filling the empty part with spaces. – Ben Nov 19 '10 at 06:19

2 Answers2

0

Do you mean sprintf()'s width format specifier (e.g. %20d)? If so, Javascript sprintf is indeed your answer.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • While you are at it. Have a look at http://documentcloud.github.com/underscore/ it includes the Javascript sprintf and has some other awesome functionality as well. – Michael Nov 19 '10 at 06:32
  • That's probably it. Thanks for your help. – Ben Nov 19 '10 at 06:35
-1

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>
Community
  • 1
  • 1
7vujy0f0hy
  • 8,741
  • 1
  • 28
  • 33