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
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.
Here’s a concise implementation for parsing UTC date strings in ISO 8601 format into Date objects in the local time zone.
function parseIsoDate(s) {
var tokens = /(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\.(\d+)/
.exec(s).slice(1);
tokens[1] -= 1;
return new Date(Date.UTC.apply(null, tokens));
}
The new Date(Date.UTC.apply(null, tokens)) trick allows the direct usage of an array of date components for the construction of a new Date instance.
Here’s a basic string formatter that takes in a format string and a variable number of arguments:
// Format string may contain variable references in the form "{i}"
// where i is the variable index
function format(fmt) {
return fmt.replace(/\{(\d+)\}/g, function (s, i) {
return arguments[i];
});
}
// Usage:
var usercnt = 45, groupcnt = 3;
format("Found {1} users and {2} groups", usercnt, groupcnt);
// Returns "Found 45 users and 3 groups"
Similarly, object property names could be used:
// Format string may contain variable references in the form "{n}"
// where n is the variable name
function format(fmt, object) {
return fmt.replace(/\{(\w+)\}/g, function (s, n) {
return object[n];
});
}
// Usage:
var results = {
usercnt: 45,
groupcnt: 3
};
format("Found {usercnt} users and {groupcnt} groups", results);
// Returns "Found 45 users and 3 groups"
Suppose you already have some items in an array and you want to append those items to a target array. You can use the concat method to create a new array that is the concatenation of the two arrays and replace the target array with the result:
var items = [ 3, 5, 7 ];
target = target.concat(items); // new instance!
You can avoid replacing the array with a new instance every time you need to append new items to it by using the push method. One thing to note is that push accepts multiple arguments and we can apply the new item array as arguments to push directly:
Array.prototype.push.apply(target, items);
// Equivalent to target.push(3, 5, 7)
// -- if the items weren't already in an array