fast-printf
Fast and spec-compliant printf
implementation for Node.js and browser.
Usage
import {
printf,
} from 'fast-printf';
console.log(printf('foo %s', 'bar'));
Handling Unbound Value References
By default, interpolating an unbound expression produces:
- The expression is left in place
- A warning is logged using roarr
i.e. printf('%s bar')
produces %s bar
.
This behavior can be overridden by configuring a fast-printf
instance using createPrintf
:
import {
createPrintf,
} from 'fast-printf';
const printf = createPrintf({
formatUnboundExpression: (
subject: string,
token: PlaceholderToken,
boundValues: any[],
): string => {
console.warn({
boundValues,
position: token.position,
subject,
}, 'referenced unbound value');
return token.placeholder;
};
});
console.log(printf('foo %s', 'bar'));
Benchmark
implementation | without_placeholders | with_string_placeholder | with_many_string_placeholders |
---|
sprintf | 31,772,029 | 4,154,748 | 637,229 |
printf | 651,970 | 373,615 | 160,795 |
fast-printf | 78,068,540 | 11,820,632 | 2,552,386 |
Results show operations per second (greater is better).
To run the benchmark yourself please see ./benchmark
.
Printf Cheatsheet
printf('%c', 'b');
printf('%C', 'b');
printf('%d', 100);
printf('%05d', 1);
printf('%5d', 1);
printf('%-5d', 1);
printf('%+5d', 1);
printf('%+5d', -1);
printf('%e', 52.8);
printf('%E', 52.8);
printf('%f', 52.8);
printf('%.1f', 1.234);
printf('%5f', 123);
printf('%05.1f', 1.234);
printf('%-5.1f', 1.234);
printf('%i', 123);
printf('%b', true);
printf('%b', 'true');
printf('%b', 1);
printf('%b', true);
printf('%b', 'true');
printf('%b', 1);
printf('%o', 8);
printf('%s', 'foo');
printf('%5s', 'foo');
printf('%-5s', 'foo');
printf('%S', 'foo');
printf('%u', 1);
printf('%u', -1);
printf('%x', 255);
printf('%%');
printf('\\%');
printf('%2$s %1$s', 'bar', 'foo');