Skip to content

Instantly share code, notes, and snippets.

@russellhaering
Created July 21, 2011 00:14
Show Gist options
  • Save russellhaering/1096232 to your computer and use it in GitHub Desktop.
Save russellhaering/1096232 to your computer and use it in GitHub Desktop.
Fast sprintf() in Javascript
/**
* Note: this only currently supports the %s and %j formatters.
*
* The first call with any given formatter will be relatively slow, but every subsequent
* call with the same formatter should be very fast (in V8).
*/
var cache = {};
var SINGLE_QUOTE = new RegExp('\'', 'g');
function populate(formatter) {
var i, type;
var key = formatter;
var prev = 0;
var arg = 1;
var builder = 'return \'';
formatter = formatter.replace(SINGLE_QUOTE, '\\\'');
for (i = 0; i < formatter.length; i++) {
if (formatter[i] === '%' && formatter[i - 1] !== '\\') {
type = formatter[i + 1];
switch (type) {
case 's':
builder += formatter.slice(prev, i) + '\' + arguments[' + arg + '] + \'';
break;
case 'j':
builder += formatter.slice(prev, i) + '\' + JSON.stringify(arguments[' + arg + ']) + \'';
break;
}
prev = i + 2;
arg++;
}
}
builder += formatter.slice(prev) + '\';';
cache[key] = new Function(builder);
}
exports.sprintf = function(formatter) {
if (!cache[formatter]) {
populate(formatter);
}
return cache[formatter].apply(null, arguments);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment