Implementation of "sprintf()" for JavaScript

Submitted by:Jhon Jhon

Date added:28 September, 2016

Category:JavaScript

A JavaScript implementation of the famous sprintf() function

Tags: javascript function , sprintf function

Code Snippet:

// Implementation of "sprintf()" for JavaScript 0.6
// Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
// All rights reserved.

FUNCTION str_repeat(i, m) {
FOR (VAR o = []; m > 0; o[--m] = i);
RETURN o.join('');
}

FUNCTION sprintf() {
VAR i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = '';
WHILE (f) {
IF (m = /^[^\x25]+/.exec(f)) {
o.push(m[0]);
}
ELSE IF (m = /^\x25{2}/.exec(f)) {
o.push('%');
}
ELSE IF (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
IF (((a = arguments[m[1] || i++]) == NULL) || (a == undefined)) {
THROW('Too few arguments.');
}
IF (/[^s]/.test(m[7]) && (TYPEOF(a) != 'number')) {
THROW('Expecting number but found ' + TYPEOF(a));
}
SWITCH (m[7]) {
CASE 'b': a = a.toString(2); BREAK;
CASE 'c': a = String.fromCharCode(a); BREAK;
CASE 'd': a = parseInt(a); BREAK;
CASE 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); BREAK;
CASE 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); BREAK;
CASE 'o': a = a.toString(8); BREAK;
CASE 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); BREAK;
CASE 'u': a = Math.abs(a); BREAK;
CASE 'x': a = a.toString(16); BREAK;
CASE 'X': a = a.toString(16).toUpperCase(); BREAK;
}
a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a);
c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
x = m[5] - String(a).length - s.length;
p = m[5] ? str_repeat(c, x) : '';
o.push(s + (m[4] ? a + p : p + a));
}
ELSE {
THROW('Huh ?!');
}
f = f.substring(m[0].length);
}
RETURN o.join('');
}
 
 

Comments