Text

Rounding with significant figures

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
Text

Parsing query string parameters into a collection

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.

Text

Parsing ISO 8601 UTC dates

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.

Text

String formatter

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"