Repeating or Padding Strings in JavaScript
Here’s a nice trick for repeating a string a given number of times.
Here’s a nice trick for repeating a string a given number of times.
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
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.
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.
I had been working on parsing the source of JavaScript function instances when I realized that Function.prototype.toString() may return parts of the original comments in the source code, depending on the browser. I’ve done a quick test to capture the different behaviours of popular browsers.
I came across yet another browser discrepancy with a rather obscure scenario: Accessing an object property from a function declaration within a with block for that object.
Here’s a quick and dirty XML/HTML generator. Without even bothering to write a new class, I simply extend an Array instance with a few helpers that can be chained.
I’ve created a bookmarklet to temporarily solve a very specific problem at hand: I’m translating a TED video into Turkish, but I don’t currently have a Turkish keyboard hooked up to my computer (it’s in a box somewhere in the basement).
Here’s a utility function for parsing query parameters:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {};
var tokens, re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
A nice things is that it’s decoupled from document.location.search.
An inadvertently skipped semicolon recently left me scratching my head over a runtime error.