bs-format
v0.0.3
Published
Value formatter and string interpolator
Downloads
1
Readme
Example
var format = require('format');
format.string('First: {0}, Second: {1}, Third: {2}', 'test', true, 42);
// First: test, Second: true, Third: 42
format.string('Mass: {0f:3} kg, Age: {0i} years, Hex ID: 0x{0i:32x}',
74.21, 26, 64206);
// Mass: 74.2 kg, Age: 26 years, Hex ID: 0xface
/*
* Optional monkey-patch:
* Adds method to String.prototype.format which proxies to format.string
*/
format.moreConflict();
/* With moreConflict called, we can use this shorthand: */
'First: {0}, Second: {1}, Third: {2}'.format('test', true, 42);
// First: test, Second: true, Third: 42
format.string(formatStr, values...);
The formatStr
string is a string which contains zero or more format specifiers.
A format specifier is contained in braces.
{spec}
Open-brace in the format string should be escaped if it is not the start of a format specifier:
not a format specifier => \{0}
is a format specifier => {0}
Remember that backslashes must also be escaped in JavaScript strings!
var format = "not a format specifier => \\{0}";
Close-brace within a format specifier must be escaped by preceeding with backslash.
{ \} }
var fmt = "true/false => \\{/} result={0b:{:\\}}";
/* true/false => {/} result={ */
format.string(fmt, true);
/* true/false => {/} result=} */
format.string(fmt, false);
The specifier contains one or more fields, separated by colons:
{f1:f2:f3}
Colons within a field must be escaped by preceeding with a backslash.
{ escape close brace \} : escape colon \: }
The first field is a numerical zero-based index, specifying the index of the value to use. The first value in the value array is "{0}", the second value in the array is "{1}" and so forth. If the index is omitted, then the next item is used:
string.format('{0i} {i} {4i} {i} {}', 0, 1, 2, 3, 4, 5, 6);
// Produces 0 1 4 5 6
string.format('{2} {} {} {}', 0, 1, 2, 3, 4, 5, 6);
// Produces 2 3 4 5
string.format('{i} {i} {i}', 0, 1, 2, 3, 4, 5, 6);
// Produces 0 1 2
string.format('{} {} {}', 0, 1, 2, 3, 4, 5, 6);
// Produces 0 1 2
The other fields depend on the type of value being formatted - see the formatters in the next section.
A character after the index indicates the formatter to use:
- int
- float
- boolean
- date
- object
- array
If not specified, format.string
will attempt to guess which formatter to use.
Guessing wrongly may produce incorrect results, so it is advised to always
specify which formatter to use.
Examples:
format.string('age: {0i} years, mass: {1f:.2} kg, active: {2b:yes:no}',
26, 74.2, true);
Produces:
age: 26 years, mass: 74.20 kg, active: yes
Syntax for individual formatters
format.array(value, formatStr)
delim : quote/escape : prefix : suffix
,:qe:[:]
- , is delimeter string to put between items.
- q char causes each item to be double-quoted.
- e char causes double-quotes in items to be escaped by backslashes.
- [ is string to put before first item.
- ] is string to put after first item.
- All fields after index are optional, e.g:
The following produce the same output:
- (blank)
- ,::
- ,::[
- ,::[:]
- Other examples:
- \n::BEGIN:END
- , :qe:function( :)
format.int(value, formatStr)
force-sign width base
[+][width][base]
- forces sign to be shown, even for non-negative numbers.
- width specified the minimum number of digits to show (zero-padding used).
- base is one of [bodx] for [b]inary, [o]ctal, [d]ecimal, he[x]. It can also be specified as bN where N is the base to use. N is in 2..36 as the base conversion is done by JS natively.
- All fields after index are optional, e.g:
The following produce the same output:
- (blank)
- 0
- 0d
- 0b10
- Other examples:
- 8b (eight binary digits e.g. byte bitmask)
- 2x (two hex digits e.g. byte in dump / hex editor)
- b36 (base-36 e.g. ???)
- 3o (three octal digits e.g. UNIX file permissions)
- (always show sign)
- +3 (always show sign, pad to at least three digits long)
- +b10 (always show sign, base-ten i.e. decimal)
format.float(value, formatStr)
force-sign significant-figures
force-sign width.places
[+][digits]
- forces sign to be shown, even for non-negative numbers.
- digits is either a number (0) specifying number of significant figures to show, or two numbers (0.0) specifying width of the integral part and the fractional part respectively.
- By default (no digits parameter) the value will be rounded.
- All fields after index are optional
- Examples:
- 4 (four significant figures)
- .3 (three decimal places)
- 2.3 (three decimal places, pad integral part to at least two digits long)
- 0.3 (same as .3)
- 1.3 (same as .3)
format.bool(value, formatStr)
true-string : other-string : false-string
[true:[other:]false]
- true is string to emit for TRUE value.
- false is string to emit for FALSE value.
- other is string to emit for non-boolean value. If not specified, then values will be co-erced to boolean true/false.
- All fields after index are optional, e.g:
- The following produce the same output:
- (blank)
- true:false
- Other examples:
- true:invalid:other ("invalid" for non-boolean values)
- yay:nay (truthy="yay", falsy="nay")
- on:off (truthy/falsy => "on"/"off")
- 1:-1:0 (true => "1", false => "0", other => "-1")
- bool true:not a bool: bool false
Testing
Running either the following
npm test
node test
will run a suite of tests and report the result to STDERR. When debugging, to run specific test(s) only, run either of:
npm test [index] [index]...
node test [index] [index] ...
For example, run:
node test 23
to execute only test #23.
Demos
The test suite can output demos in Markdown format. To generate this, run:
node test md > TESTS.md
The usual test output will be logged to STDERR, but the test cases will be printed to STDOUT, complete with source code & expected result & actual result.