October 2008
4 posts
1 tag
Automatic Table of Contents Generation
Here’s a JavaScript snippet 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.
For example, for a document...
2 tags
Timing Code Accurately
The most common approach to time a function or a segment of code is to repeat it many times in a loop, measure the time the entire loop takes and then divide that number with the number of iterations. However, this approach disregards the overhead of the loop. This can be remedied with a slight modification to the loop.
Illustrating the problem with JavaScript (although this method applies to all...
1 tag
Rounding to a Certain Significant Figures in...
A function for rounding a 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
1 tag
Repeating or Padding Strings in JavaScript
Here’s a nice trick for repeating a string a given number of times.
Let’s say you want to create a string with the characters “ABC” repeated 5 times. The most straightforward approach that you could take 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 can avoid repeated...