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. Read the rest of this entry »