Archive for October, 2008

Automatic Table of Contents Generation

October 19th, 2008

Here’s a JavaScript snipplet for automatically generating a table of contents based on headings in a document. It will traverse all <h1>, <h2>, <h3>, etc. elements, add anchors (<a>) to them and generate nested unordered lists (<ul>, <li>) with links to the now anchored headings. The nesting honors the hierarchy of the headings. Read the rest of this entry »


Timing Code Accurately

October 19th, 2008

The most common approach to time a function or a segment of code is to repeat it a lot of times in a loop, measure the time the entire loop takes and then divide that number with the number of iterations. Illustrating this with JavaScript (although this method applies to all languages):

var start = new Date(); // Get current time

for (var i = 0; i < n; i++) {
    myFunction();
}

var finish = new Date(): // Get current time

var ntimes = finish - start; // Elapsed time for n iterations
var once = ntimes / n; // Average time for one function call

However, this doesn’t really measure just how much time n calls to myFunction took. There’s also the overhead of the loop itself. What we actually end up measuring is not just the time to execute one call to myFunction but also the overhead of one iteration: Read the rest of this entry »


Rounding to a Certain Significant Figures in JavaScript

October 14th, 2008

A recent question at stackoverflow.com prompted me to take a stab at implementing a function for rounding a given decimal number to a given number of significant figures (or digits).

function sigFigs(n, sig) {
    var mult = Math.pow(10,
        sig - Math.floor(Math.log(n) / Math.LN10) - 1);
    return Math.round(n * mult) / mult;
}

alert(sigFigs(1234567, 3)); // Gives 1230000
alert(sigFigs(0.06805, 3)); // Gives 0.0681
alert(sigFigs(5, 3)); // Gives 5

Repeating or Padding Strings in JavaScript

October 13th, 2008

Here’s a nice trick for repeat a string a given number of times. Let’s say you want to create string with the characters “ABC” repeated 5 times. The most straightforward approach that you could use is to set up a for loop to append “ABC” to a string 5 times:

var s = "";
for (var i = 0; i < 5; i++) {
    s += "ABC";
}
alert(s); // Gives you "ABCABCABCABCABC"

You could also have avoided all the concatenation by using an intermediary Array:

var arr = [];
for (var i = 0; i < 5; i++) {
    arr.push("ABC");
}
alert(arr.join("")); // Gives you "ABCABCABCABCABC"

We populated an array with 5 instances of the string “ABC” and then joined the array items into a single string with an empty string as the delimiter (i.e. no delimiter). What may not be immediately obvious is that we could have as well done the opposite and populate the array with 5 + 1 empty strings (or undefined slots) and used “ABC” as the delimiter:

var arr = new Array(6);
alert(arr.join("ABC")); // Gives you "ABCABCABCABCABC"

Or in short form:

alert((new Array(6)).join("ABC")); // Gives you "ABCABCABCABCABC"

This can be used for padding a string with a given string, repeated a given number of times:

/**
 * Left-pad a number with zeros so that it's at least the given
 * number of characters long
 * @param n   The number to pad
 * @param len The desired length
 */
function leftPad(n, len) {
    return (new Array(len - String(n).length + 1)).join("0").concat(n);
}

alert(leftPad(42, 6)); // Gives you "000042"