C's stdio.sprintf in JavaScript

Here’s what our current JavaScript equivalent to C's sprintf found in the stdio.h header file looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
function pad (str, minLength, padChar, leftJustify) {
const diff = minLength - str.length
const padStr = padChar.repeat(Math.max(0, diff))

return leftJustify ? str + padStr : padStr + str
}

module.exports = function sprintf (format, ...args) {
// original by: Rafał Kukawski
// example 1: sprintf('%+10.*d', 5, 1)
// returns 1: ' +00001'
const placeholderRegex = /%(?:(\d+)\$)?([-+#0 ]*)(\*|\d+)?(?:\.(\*|\d*))?([\s\S])/g

let index = 0

return format.replace(placeholderRegex, function (match, param, flags, width, prec, modifier) {
const leftJustify = flags.includes('-')

// flag '0' is ignored when flag '-' is present
const padChar = leftJustify ? ' '
: flags.split('').reduce((pc, c) => [' ', '0'].includes(c) ? c : pc, ' ')

const positiveSign = flags.includes('+') ? '+' : flags.includes(' ') ? ' ' : ''

const minWidth = width === '*' ? args[index++] : +width || 0
let precision = prec === '*' ? args[index++] : +prec

if (param && !+param) {
throw Error(`Param index must be greater than 0`)
}

if (param && +param > args.length) {
throw Error(`Too few arguments`)
}

// compiling with default clang params, mixed positional and non-positional params
// give only a warning
const arg = param ? args[param - 1] : args[index++]

if (precision === undefined || isNaN(precision)) {
precision = 'eEfFgG'.includes(modifier) ? 6 : (modifier === 's' ? String(arg).length : undefined)
}

switch (modifier) {
case '%':
return '%'
case 'd':
case 'i': {
const number = Math.trunc(+arg || 0)
const abs = Math.abs(number)
const prefix = number < 0 ? '-' : positiveSign

const str = pad(abs.toString(), precision || 0, '0', false)

if (padChar === '0') {
return prefix + pad(str, minWidth - prefix.length, padChar, leftJustify)
}

return pad(prefix + str, minWidth, padChar, leftJustify)
}
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G': {
const number = +arg
const abs = Math.abs(number)
const prefix = number < 0 ? '-' : positiveSign

const op = [
Number.prototype.toExponential,
Number.prototype.toFixed,
Number.prototype.toPrecision
]['efg'.indexOf(modifier.toLowerCase())]

const tr = [
String.prototype.toLowerCase,
String.prototype.toUpperCase
]['eEfFgG'.indexOf(modifier) % 2]

const isSpecial = isNaN(abs) || !isFinite(abs)

let str = isSpecial ? abs.toString().substr(0, 3) : op.call(abs, precision)

if (padChar === '0' && !isSpecial) {
return prefix + pad(tr.call(str), minWidth - prefix.length, padChar, leftJustify)
}

return pad(tr.call(prefix + str), minWidth, isSpecial ? ' ' : padChar, leftJustify)
}
case 'b':
case 'o':
case 'u':
case 'x':
case 'X': {
const number = +arg || 0
const intVal = Math.trunc(number) + (number < 0 ? 0xFFFFFFFF + 1 : 0)
const base = [2, 8, 10, 16, 16]['bouxX'.indexOf(modifier)]
const prefix = intVal && flags.includes('#') ? ['', '0', '', '0x', '0X']['bouxXX'.indexOf(modifier)] : ''

if (padChar === '0' && prefix) {
return prefix + pad(pad(intVal.toString(base), precision, '0', false), minWidth - prefix.length, padChar, leftJustify)
}

return pad(prefix + pad(intVal.toString(base), precision, '0', false), minWidth, padChar, leftJustify)
}
case 'p':
case 'n': {
throw Error(`'${modifier}' modifier not supported`)
}
case 's': {
return pad(String(arg).substr(0, precision), minWidth, padChar, leftJustify)
}
case 'c': {
// extension, if arg is string, take first char
const chr = typeof arg === 'string' ? arg.charAt(0) : String.fromCharCode(+arg)
return pad(chr, minWidth, padChar, leftJustify)
}
case 'a':
case 'A':
throw Error(`'${modifier}' modifier not yet implemented`)
default:
// for unknown modifiers, return the modifier char
return modifier
}
})
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/c/stdio/sprintf'). You could also require the stdio module in full so that you could access stdio.sprintf instead.

If you intend to target the browser, you can then use a module bundler such as Browserify, webpack or rollup.js.

ES5/ES6

This function targets ES5, but as of Locutus 2.0.2 we also support ES6 functions. Locutus transpiles to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1sprintf('%+10.*d', 5, 1)' +00001'

Ehm.. Only 3 C functions in all of Locutus?

We could still assimilate many more functions to this language. We only just rolled out multilingual support to Locutus. If you fancy a challenge, we'd love your help expanding that. For instance, you could:

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More C stdio functions