rsformat 0.2.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,74 +2,106 @@
2
2
 
3
3
  RSFormat is a string formatting/printing library for JavaScript. It offers a minimal, yet powerful and flexible alternative to the string formatting and printing provided by `console.log`.
4
4
 
5
+ ```js
6
+ import { rs, println } from 'rsformat';
7
+
8
+ let s = rs`${15} is ${15}:#X in hex`;
9
+ // s == '15 is 0xF in hex'
10
+
11
+ println(rs`${'a'}:^5`);
12
+ // Prints ' a '
13
+ ```
14
+
5
15
  ## Motivation
6
16
 
7
17
  `console.log` is an odd method: its output can be affected by functions called before/after it (such as `console.group`), or their order affected by what parameters there are. For example, when calling `console.log(string, number)`, number can come either after or inside `string` depending on the value of `string`.
8
18
 
9
- RSFormat provides alternative functions with standardised behaviour: its `format`, `println` and all other functions will always output in the same manner, and have a standardised syntax which will only print the initial string, formatted with the parameters provided afterwards.
19
+ This behaviour has largely been superseded at a language level by template literals, which allow formatting of parameters directly inside the templates, causing these methods to have unnecessary overhead and undesired behaviour.
10
20
 
11
- Rust formatting also includes a lot of convenient operators for formatting text, such as padding/alignment, printing numbers in a given base, specifying decimal precision, etc.. This makes it a more ergonomic and convenient approach to printing things to the console.
21
+ RSFormat builds onto template literals by implementing Rust-style format specifiers and lightweight printing functions. Rust formatting includes a lot of convenient operators for formatting text, such as padding/alignment, printing numbers in a given base, specifying decimal precision, etc.
12
22
 
13
23
  ## Usage
14
24
 
15
- you can install rsformat using [npm](https://www.npmjs.com/package/rsformat):
25
+ You can install RSFormat from [npm](https://www.npmjs.com/package/rsformat):
16
26
 
17
- ```
27
+ ```sh
18
28
  npm install rsformat
19
29
  ```
20
30
 
21
31
  ### Basic formatting and printing to console
22
32
 
23
- RSFormat functions are called using a format string, and any number of format arguments following it.
33
+ The `rs` template tag can be used to enable rust-style formatting in a template.
24
34
 
25
- Any instance of `{}` in the format strings will get replaced with a value.
26
-
27
- You can specify what value you want in the parameters by using a number inside the insertion point.
35
+ To reference a previous or following argument, use `rs.ref` with the argument number. This is useful if you want to reuse a complicated expression without having to declare it separately.
28
36
 
29
37
  ```js
30
- import { format, println } from 'rsformat'; // ESM
31
- const { format, println } = require('rsformat'); // CommonJS
38
+ import { rs, println } from 'rsformat'; // ESM
39
+ const { rs, println } = require('rsformat'); // CommonJS
32
40
 
33
- let name = 'everyone';
41
+ let number = 14;
34
42
 
35
- let greeting = format('Hello {}!', name); // Evaluates to the string 'Hello, everyone!'
43
+ let info = rs`${number+1} is ${rs.ref(0)}:x in hex`; // info == '15 is f in hex'
44
+ ```
36
45
 
37
- println('I have {1} apples and {0} oranges', 13, 14); // Will print 'I have 14 apples and 13 oranges' to the console
46
+ > NB: templates tagged with `rs` are instances of a special class `RsString` that extends `String`, rather than a primitive value. This is to enable colors for debug formatting inside the printing functions. This difference should not affect normal usage, but `rs.raw` can be used as an alternative tag to get a primitive `string` with ANSI control characters escaped.
47
+
48
+ The printing functions can be called with plain strings, instances of `String` or templates formatted with `rs`:
49
+
50
+ ```ts
51
+ println('Hello World');
52
+ println(`This template did ${'Not'} need fancy formatting`);
53
+ println(rs`...`);
38
54
  ```
39
55
 
40
56
  ### Format Specifiers
41
57
 
42
- Format specifiers can be used by adding `:` inside the insertion point (after the optional argument number), and will format the value differently inside the string. See the [rust format docs](https://doc.rust-lang.org/std/fmt/#syntax) for more detailed information on format specifiers.
58
+ Format specifiers can be used by adding `:` after the format argument, and will format the value differently inside the string. See the [rust format docs](https://doc.rust-lang.org/std/fmt/) for more detailed information on format specifiers.
43
59
 
44
- This implementation differs from the rust one in a few ways:
60
+ This implementation differs from the Rust one in a few ways:
45
61
 
46
- - Named arguments before or in format specifiers or in values aren't allowed, only numbers can be used.
47
- - The `-` sign (unused in rust) is unsupported.
62
+ - Rather than escaping the braces using `{{` or `}}`, the formatting colon can be escaped using `::`.
63
+ - Different parameters are referenced using `rs.ref(n)` rather than the number literal `n`.
64
+ - To separate a formatting specifier from the rest of the string without adding a space, an extra closing colon must be added (eg. `:#?:foo` - specifier gets parsed as `:#?`)
65
+ - The `-` sign (unused in Rust) will add a space if the number is positive to align it with negative numbers without showing a `+`.
48
66
  - Pointer format type `p` is unsupported.
49
67
  - Hexadecimal debug types `x?` and `X?` are unsupported.
50
- - Specifying precision with `*` is unsupported.
68
+ - Specifying precision dynamically with `*` is unsupported. Instead, precision and width can both be specified dynamically by using a separate number parameter in place of the number.
69
+ - New format types have been added:
70
+ - `N` for uppercase ordinal suffixing of numbers (rounded to integers)
71
+ - `n` for lowercase ordinal suffixing of numbers (rounded to integers)
51
72
 
52
73
  #### Different formatting types
53
74
 
75
+ The debug format specifier `?` uses `util.inspect` to stringify the parameter rather than `toString`.
76
+
54
77
  ```js
55
- // Debug format specifier: ?, uses util.inspect rather than toString
78
+ let obj = { a: 1 };
79
+ println(rs`${obj}`); // prints '[object Object]'
80
+ println(rs`${obj}:?`); // prints '{ a: 1 }'
81
+ ```
56
82
 
57
- println('{}', { a: 1 }); //prints '[object Object]'
58
- println('{:?}', { a: 1 }); //prints "{ a:1 }"
83
+ The provided printing functions will display colors in the output of `util.inspect`, but otherwise it will be formatted without color.
59
84
 
60
- // Number base specifiers: x, X, b, o - for lower/uppercase hexadecimal, binary, octal
85
+ The specifiers `b`,`o`,`x`,`X`,`e`,`E`,`n`,`N` will convert a `number` or `bigint` parameter to:
86
+ - `b`: binary
87
+ - `o`: octal
88
+ - `x`/`X`: lowercase/uppercase hexadecimal
89
+ - `e`/`E`: lowercase/uppercase scientific notation
90
+ - `n`/`N`: lowercase/uppercase ordinal suffixed string (rounded to integer)
61
91
 
62
- format('{} is {0:x} in hex, {0:b} in binary and {0:o} in octal', 15); // '15 is f in hex, 1111 in binary and 17 in octal'
92
+ ```js
93
+ let advancedInfo = (n) => rs`${n} is ${n}:x in hex, ${n}:b in binary and ${n}:o in octal`;
63
94
 
64
- // Scientific notation specifiers: e, E - for lower/uppercase scientific notation
95
+ advancedInfo(15); // '15 is f in hex, 1111 in binary and 17 in octal'
65
96
 
66
97
  let hugeNumber = 1000n;
67
- format('{:E}', hugeNumber); // '1E3';
98
+ let science = rs`${hugeNumber}:E`; // '1E3'
99
+ let ordinal = rs`${hugeNumber}:n`; // '1000th'
68
100
  ```
69
101
 
70
102
  #### Padding, Alignment
71
103
 
72
- Values can be aligned using any fill character (will default to a space ` `), and either left, center or right aligned with `<`, `^` or `>` respectively (will default to right alignment `>`). You will also have to specify a width with an integer after the alignment:
104
+ Values can be aligned using any fill character (will default to a space ` `), and either left, center or right aligned with `<`, `^` or `>` respectively (will default to right alignment `>`). You will also have to specify a width with an integer after the alignment, or provide a separate number parameter.
73
105
 
74
106
  ```js
75
107
  /*
@@ -80,91 +112,52 @@ Will print a pyramid of 'a's:
80
112
  */
81
113
  let pyramidLevels = ['a', 'aaa', 'aaaaa'];
82
114
  for(let value of pyramidLevels) {
83
- println('{:^5}', value);
115
+ println(rs`${value}:^5`);
84
116
  }
85
117
  ```
86
118
 
87
119
  ```js
88
- format('{:.>7}', [1,2]); // '....1,2'
120
+ rs`${[1,2]}:.>${7}` // '....1,2'
89
121
  ```
90
122
 
91
123
  #### Pretty Printing
92
124
 
93
- In some instances (namely debug, binary, octal and hexadecimal formatting), adding a `#` before the format specifier will use an alternative 'pretty' printing style. This amounts to using non-compact `util.inspect` for debug printing (spanning multiple lines), and adding 0b/0o/0x as a prefix for the numbers formatted as powers of two.
125
+ In some instances (namely debug, binary, octal and hexadecimal formatting), adding a `#` before the format specifier will use an alternative 'pretty' printing style. This amounts to using multiline `util.inspect` for debug printing (spanning multiple lines), and adding `0b`/`0o`/`0x` as a prefix for the numbers in the respective bases.
94
126
 
95
127
  ```js
96
- format('{:#X}', 255); // '0xFF'
128
+ rs`${255}:#X` // '0xFF'
97
129
  ```
98
130
 
99
131
  #### Specific Number Formatting
100
132
 
101
- Specifically for `number` and `bigint` values, a 0 can be placed before the width to pad the number with 0s instead. This will account for signs and possible formatting differences.
133
+ Specifically for `number` and `bigint` values, a `0` can be placed before the width to pad the number with zeroes instead. This will account for signs and possible formatting differences.
102
134
 
103
135
  ```js
104
- format('{:#07x}', 15) // '0x0000F'
136
+ rs`${15}:#07x` // '0x0000F'
105
137
  ```
106
138
 
107
- Decimal precision can be specified for numbers by adding a . and specifying an integer for precision.
139
+ Decimal precision can be specified for numbers by adding a `.` and specifying an integer for precision. An additional parameter can also be provided to do this dynamically.
108
140
 
109
141
  ```js
110
- format('{:.3}', 1.23456789); // '1.234'
111
- format('{:.3}', -1); // '-1.000'
142
+ rs`${1.23456789}:.3` // '1.234'
143
+ rs`${-1}:.${3}` // '-1.000'
112
144
  ```
113
145
 
114
- Adding a + to the formatting specifier will print the sign regardless of whether the number is negative.
146
+ Adding a `+` to the formatting specifier will print the sign regardless of whether the number is negative.
147
+ Adding a `-` will instead add a space if the number is positive.
115
148
 
116
149
  ```js
117
- format('{:+}', 1); // '+1'
150
+ rs`${1}:+` // '+1'
151
+ rs`${1}:-` // ' 1'
118
152
  ```
119
153
 
120
- ## Custom output
121
-
122
- If you want to use the print function to output to anything other than `process.stdout` and `process.stderr`, you can import the `Printer` function to create your own print functions, using any output and error streams that are instances of node's `Writable`.
154
+ ## Older versions of RSFormat
123
155
 
124
- ```ts
125
- // Custom output example (ts)
126
- import { Printer } from 'rsformat/print';
127
- import { Writable } from 'stream';
128
-
129
- let someOutputStream: Writable = /* ... */;
130
- let someErrorStream: Writable = /* ... */;
131
-
132
- let { print, println, eprint, eprintln } = Printer(someOutputStream, someErrorStream);
133
- ```
134
-
135
- ## A Note on Performance
136
-
137
- You might think that these utilities might have a performance impact on RSFormat's printing functions. And while they do, the functions are still consistently faster than `console.log`.
138
-
139
- A simple benchmark setup like the one below will demonstrate that `println` is more performant, even when doing things like base conversions and text alignment, compared to `console.log` logging a simple string:
156
+ Versions of RSFormat on npm prior to `1.0.0` provide formatting and printing functions that are more similar in syntax to Rust, using plain strings instead of tagged templates:
140
157
 
141
158
  ```js
142
- // benchmark.mjs
143
- import { println } from 'rsformat';
144
-
145
- const time = (fn, iter) => {
146
- let time = Date.now();
147
- while (iter-- > 0) {
148
- fn();
149
- }
150
- return Date.now() - time;
151
- }
152
-
153
- let iterations = 100000;
154
-
155
- let logTime = time(() => console.log('hello'), iterations);
156
- let printlnTime = time(() => println('{:>+#7X}', 255), iterations);
157
-
158
- println('console.log time for {} executions: {}ms', iterations, logTime);
159
- println('rsformat.println time for {} executions: {}ms', iterations, printlnTime);
160
- ```
161
-
162
- ```
163
- > node benchmark.mjs
164
- ...After a lot of output...
165
-
166
- console.log time for 100000 executions: 7217ms
167
- rsformat.println time for 100000 executions: 5900ms
159
+ import { format } from 'rsformat';
160
+ format('{} is {0:#x} in hex', 15); // '15 is 0xf in hex'
168
161
  ```
169
162
 
170
- _Tested on node.js using a Windows laptop on an Intel core I7-1360P, on battery power. Performance will vary, but this benchmark was just to show that RSFormat has no performance penalty._
163
+ See the `old` branch for more detailed documentation. The last version to use this formatting was `0.2.5`.
package/lib/format.d.ts CHANGED
@@ -1,17 +1,48 @@
1
1
  /**
2
- * Format a string similarly to rust's format! macro.
2
+ * Type representing a string formatted by `rs`.
3
+ * An extension of `String`.
4
+ */
5
+ export declare class RsString extends String {
6
+ /**
7
+ * A version of the string that includes ANSI escape codes for debug formatting.
8
+ */
9
+ colored: string;
10
+ constructor(strings: TemplateStringsArray, params: any[]);
11
+ toString(debugColors?: boolean): string;
12
+ }
13
+ /**
14
+ * Format a template literal with rust-style formatting and return it as a raw and colored string.
15
+ *
16
+ * @param strings String parts of the template
17
+ * @param params Template parameters
3
18
  *
4
- * @param str String used for formatting
5
- * @param params Parameters to be inserted into the format string
19
+ * @returns An object with raw and colored versions of the formatted parameter
6
20
  */
7
- export declare function format(str: string, ...params: any[]): string;
21
+ export declare function buildString(strings: TemplateStringsArray, params: any[]): {
22
+ raw: string;
23
+ colored: string;
24
+ };
25
+ type AlignDirection = '<' | '^' | '>';
26
+ type Sign = '-' | '+' | '';
27
+ type FormatType = '?' | 'o' | 'x' | 'X' | 'b' | 'e' | 'E' | 'n' | 'N' | '';
28
+ type FormatSpecifier = {
29
+ fill: string;
30
+ align: AlignDirection;
31
+ force_sign: Sign;
32
+ pretty: boolean;
33
+ pad_zeroes: boolean;
34
+ width: number;
35
+ precision: number;
36
+ type: FormatType;
37
+ };
8
38
  /**
9
- * Raw formatting behaviour function called by `format` and printing functions.
39
+ * Format a parameter as a string according to a specifier.
40
+ * Will include colors in the output of debug formating
10
41
  *
11
- * @param str String used for formatting
12
- * @param params Parameters to be inserted into the format string
13
- * @param options Options passed into formatting (Whether to use colors in debug formatting - false by default)
42
+ * @param param parameter to format
43
+ * @param format format specifier object
44
+ * @param debugColors whether to use colors in debug formatting
45
+ * @returns `param` as a formatted string
14
46
  */
15
- export declare function fmt_raw(str: string, params: any[], options?: {
16
- colors: boolean;
17
- }): string;
47
+ export declare function formatParam(param: any, format: FormatSpecifier): string;
48
+ export {};
package/lib/format.js CHANGED
@@ -1,218 +1,311 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fmt_raw = exports.format = void 0;
4
- const node_util_1 = require("node:util");
6
+ exports.formatParam = exports.buildString = exports.RsString = void 0;
7
+ const node_util_1 = __importDefault(require("node:util"));
8
+ const is_digit = (c) => c >= '0' && c <= '9';
9
+ const error = (param, char, reason) => new Error(`rs[param ${param}, char ${char}] ${reason}`);
5
10
  /**
6
- * Regex to match for possible formatting insertion points.
7
- * Similar to the way formatting is parsed in rust,
8
- * but with a few key differences:
9
- * - Named arguments before format specifiers aren't allowed, only numbers can be used.
10
- * - The - sign (unused in rust) is unsupported.
11
- * - Pointer format type 'p' is unsupported.
12
- * - Hexadecimal debug types 'x?' and 'X?' are unsupported.
13
- * - Specifying precision with * is unsupported.
14
- *
15
- * The formatter currently matches with a regex
16
- * instead of a full-blown parser for simplicity
17
- * and performance, as built-in regex matching is
18
- * likely to be faster than a js-implemented parser.
19
- * However, this will not match incorrectly formatted
20
- * insertion points.
11
+ * Type representing a string formatted by `rs`.
12
+ * An extension of `String`.
21
13
  */
22
- const FORMAT_REGEX = (/\{{2}|\}{2}|\{(\d*?)(?::(?:(.?)(\^|>|<))?(\+)?(#)?(0)?(\d*)?(\.\d*)?(\?|o|x|X|b|e|E)?)?\}/g);
23
- /**
24
- * Format a string similarly to rust's format! macro.
25
- *
26
- * @param str String used for formatting
27
- * @param params Parameters to be inserted into the format string
28
- */
29
- function format(str, ...params) {
30
- return fmt_raw(str, params);
14
+ class RsString extends String {
15
+ /**
16
+ * A version of the string that includes ANSI escape codes for debug formatting.
17
+ */
18
+ colored;
19
+ constructor(strings, params) {
20
+ let { raw, colored } = buildString(strings, params);
21
+ super(raw);
22
+ this.colored = colored;
23
+ }
24
+ toString(debugColors = false) {
25
+ if (debugColors)
26
+ return this.colored;
27
+ return this.valueOf();
28
+ }
31
29
  }
32
- exports.format = format;
30
+ exports.RsString = RsString;
33
31
  /**
34
- * Raw formatting behaviour function called by `format` and printing functions.
32
+ * Format a template literal with rust-style formatting and return it as a raw and colored string.
33
+ *
34
+ * @param strings String parts of the template
35
+ * @param params Template parameters
35
36
  *
36
- * @param str String used for formatting
37
- * @param params Parameters to be inserted into the format string
38
- * @param options Options passed into formatting (Whether to use colors in debug formatting - false by default)
37
+ * @returns An object with raw and colored versions of the formatted parameter
39
38
  */
40
- function fmt_raw(str, params, options = { colors: false }) {
41
- // Counter used for insertion of unnumbered values
42
- let param_counter = 0;
43
- str = str.replace(FORMAT_REGEX, ($, $param_number, $fill_character, $align_direction, $sign, $pretty, $pad_zeroes, $width, $precision, $type) => {
44
- // Return a bracket if the regex matched an escaped bracket
45
- if ($ === '{{') {
46
- return '{';
47
- }
48
- if ($ === '}}') {
49
- return '}';
50
- }
51
- // Process parameter number; increment param_counter if not included
52
- let param = $param_number === ''
53
- ? params[param_counter++]
54
- : params[+$param_number];
55
- if (param === undefined) {
56
- throw new Error(`parameter ${$param_number || param_counter - 1} either NaN or not provided`);
57
- }
58
- let param_type = typeof param;
59
- let true_length = -1;
60
- // Process parameter type
61
- switch ($type) {
39
+ function buildString(strings, params) {
40
+ let out = strings[0];
41
+ for (let i = 1; i < strings.length; ++i) {
42
+ let string = strings[i];
43
+ let param = params[i - 1];
44
+ // Resolve parameter references recursively
45
+ while (typeof param == 'object' && '__rs_param_ref' in param) {
46
+ let ref_number = param.__rs_param_ref;
47
+ if (typeof ref_number != 'number'
48
+ || ref_number < 0 || ref_number >= params.length) {
49
+ throw new Error(`Parameter ${i - 1}: Invalid reference`);
50
+ }
51
+ if (ref_number == i - 1)
52
+ throw new Error(`Parameter ${i - 1} references itself recursively`);
53
+ param = params[param.__rs_param_ref];
54
+ }
55
+ // Parse format specifier
56
+ // If the string starts with a single : it has a format specifier,
57
+ // If it has two the first : is being escaped and can be removed
58
+ if (string[0] == ':') {
59
+ if (string[1] == ':') {
60
+ out += param.toString() + string.substring(1);
61
+ continue;
62
+ }
63
+ }
64
+ else {
65
+ out += param.toString() + string;
66
+ continue;
67
+ }
68
+ ;
69
+ // Keep track of our index in the string to slice the format specifier later
70
+ let idx = 1;
71
+ // Compute format based on string
72
+ let fill = ' ', align = '>', force_sign = '', pretty = false, pad_zeroes = false, width = 0, precision = -1, format_type = '';
73
+ // Fill/align
74
+ // If the next character is align, then the current is the fill
75
+ if (string[idx + 1] == '<' || string[idx + 1] == '^' || string[idx + 1] == '>') {
76
+ fill = string[idx++];
77
+ }
78
+ if (string[idx] == '<' || string[idx] == '^' || string[idx] == '>') {
79
+ align = string[idx++];
80
+ }
81
+ // Force sign
82
+ if (string[idx] == '+' || string[idx] == '-')
83
+ force_sign = string[idx++];
84
+ // Pretty formatting
85
+ if (string[idx] == '#')
86
+ pretty = true, idx++;
87
+ // Padding numbers with zeroes
88
+ if (string[idx] == '0')
89
+ pad_zeroes = true, idx++;
90
+ // Width
91
+ if (is_digit(string[idx])) {
92
+ let width_substring_start = idx++;
93
+ while (is_digit(string[idx]))
94
+ idx++;
95
+ width = Number(string.substring(width_substring_start, idx));
96
+ }
97
+ else if (idx == string.length) {
98
+ // Grab the next parameter and fuse the string with the next one
99
+ width = params[i];
100
+ if (typeof width != 'number')
101
+ throw error(i - 1, idx, `Expected a number or number parameter for width specifier (found ${string[idx] ? "'" + string[idx] + "'" : typeof width + ' parameter'}).\nIf the next parameter was not meant to be a width number, add a : to the end of the formatting specifier.`);
102
+ string += strings[++i];
103
+ }
104
+ // Precision
105
+ if (string[idx] == '.') {
106
+ if (!is_digit(string[++idx])) {
107
+ // Grab the next parameter and fuse the string with the next one
108
+ precision = params[i];
109
+ if (typeof precision != 'number')
110
+ throw error(i - 1, idx, `Expected a number or number parameter for precision specifier after . (found ${string[idx] ? "'" + string[idx] + "'" : typeof width + ' parameter'}).\nIf the next parameter was not meant to be a precision number, add a : to the end of the formatting specifier.`);
111
+ string += strings[++i];
112
+ }
113
+ else {
114
+ let precision_substring_start = idx;
115
+ while (is_digit(string[idx]))
116
+ idx++;
117
+ precision = Number(string.substring(precision_substring_start, idx));
118
+ }
119
+ }
120
+ // Format type
121
+ switch (string[idx]) {
122
+ case '?':
62
123
  case 'o':
63
- param = param.toString(8);
64
- break;
65
124
  case 'x':
66
- param = param.toString(16);
67
- break;
68
125
  case 'X':
69
- param = param.toString(16).toUpperCase();
70
- break;
71
126
  case 'b':
72
- param = param.toString(2);
73
- break;
74
127
  case 'e':
75
- switch (param_type) {
76
- case 'number':
77
- param = param.toExponential();
78
- break;
79
- case 'bigint':
80
- param = param.toLocaleString('en-US', {
81
- notation: 'scientific',
82
- maximumFractionDigits: 20,
83
- }).toLowerCase();
84
- break;
85
- default:
86
- param = param.toString();
87
- break;
88
- }
89
- break;
90
128
  case 'E':
91
- switch (param_type) {
92
- case 'number':
93
- param = param.toExponential().toUpperCase();
94
- break;
95
- case 'bigint':
96
- param = param.toLocaleString('en-US', {
97
- notation: 'scientific',
98
- maximumFractionDigits: 20
99
- });
100
- break;
101
- default:
102
- param = param.toString();
103
- break;
104
- }
105
- break;
106
- case '?':
107
- // Do not force sign, pad with zeroes or align to precision when using debug formatting
108
- $sign = undefined;
109
- $pad_zeroes = undefined;
110
- $precision = undefined;
111
- true_length = (0, node_util_1.inspect)(param, {
112
- depth: Infinity,
113
- colors: false,
114
- compact: $pretty !== '#'
115
- }).length;
116
- param = (0, node_util_1.inspect)(param, {
117
- depth: Infinity,
118
- colors: options.colors,
119
- compact: $pretty !== '#'
120
- });
121
- break;
122
- default:
123
- param = param.toString();
124
- break;
129
+ case 'n':
130
+ case 'N':
131
+ format_type = string[idx++];
125
132
  }
126
- ;
127
- if (true_length == -1) {
128
- true_length = param.length;
129
- }
130
- // Compute radix-point precision on numbers
131
- if (param_type == 'number' && $precision) {
132
- let [pre, post] = param.split('.');
133
- let precision = +$precision.substring(1, $precision.length);
134
- if (!precision) { // precision = 0, do not include radix point
135
- param = pre;
136
- }
137
- else {
138
- post = ((post || '') + '0'.repeat(precision)).slice(0, precision);
139
- param = pre + '.' + post;
140
- // Update true length for fill/align
141
- true_length = param.length;
142
- }
133
+ // End of specifier
134
+ if (string[idx] == ':') {
135
+ idx++;
143
136
  }
144
- let width;
145
- if ($width === undefined) {
146
- width = 0;
137
+ else if (string[idx] != ' ' && string[idx] !== undefined) {
138
+ throw error(i - 1, idx, `Expected colon (':') or space (' ') at end of formatting specifier (found '${string[idx]}')`);
147
139
  }
148
- else {
149
- width = +$width;
150
- if (Number.isNaN(width))
151
- throw new Error(`invalid width specifier '${$width}' (must be an integer)`);
152
- }
153
- let filled = false;
154
- if ((param_type == 'number') || (param_type == 'bigint')) {
155
- // Compute parameter sign
156
- let maybe_sign = param.substring(0, 1);
157
- if (maybe_sign === '-') {
158
- param = param.substring(1, param.length);
140
+ // Format parameter according to specifier
141
+ let formatted = formatParam(param, {
142
+ fill,
143
+ align,
144
+ force_sign,
145
+ pretty,
146
+ pad_zeroes,
147
+ width,
148
+ precision,
149
+ type: format_type
150
+ });
151
+ out += formatted + string.substring(idx);
152
+ }
153
+ return { raw: node_util_1.default.stripVTControlCharacters(out), colored: out };
154
+ }
155
+ exports.buildString = buildString;
156
+ /**
157
+ * Format a parameter as a string according to a specifier.
158
+ * Will include colors in the output of debug formating
159
+ *
160
+ * @param param parameter to format
161
+ * @param format format specifier object
162
+ * @param debugColors whether to use colors in debug formatting
163
+ * @returns `param` as a formatted string
164
+ */
165
+ function formatParam(param, format) {
166
+ let param_type = typeof param;
167
+ // Process parameter type
168
+ switch (format.type) {
169
+ case 'o':
170
+ param = param.toString(8);
171
+ break;
172
+ case 'x':
173
+ param = param.toString(16);
174
+ break;
175
+ case 'X':
176
+ param = param.toString(16).toUpperCase();
177
+ break;
178
+ case 'b':
179
+ param = param.toString(2);
180
+ break;
181
+ case 'e':
182
+ case 'E':
183
+ if (param_type != 'number' && param_type != 'bigint') {
184
+ param = param.toString();
185
+ break;
159
186
  }
160
- else if ($sign === '+') {
161
- maybe_sign = '+';
187
+ param = param.toLocaleString('en-US', { notation: 'scientific', maximumFractionDigits: 20 });
188
+ if (format.type == 'e')
189
+ param = param.toLowercase();
190
+ break;
191
+ case 'n':
192
+ case 'N':
193
+ if (param_type != 'number' && param_type != 'bigint') {
194
+ param = param.toString();
195
+ break;
162
196
  }
163
- else {
164
- maybe_sign = '';
197
+ // Round and add suffix
198
+ if (param_type == 'number')
199
+ param = Math.round(param);
200
+ param = param.toString();
201
+ let last_2_digits = param.substring(param.length - 2);
202
+ if (last_2_digits == '11' || last_2_digits == '12' || last_2_digits == '13') {
203
+ param = param + 'th';
165
204
  }
166
- // If pretty printing is enabled and the formating calls for a prefix, add it
167
- if ($pretty === '#') {
168
- switch ($type) {
169
- case 'o':
170
- maybe_sign += "0o";
205
+ else
206
+ switch (last_2_digits[last_2_digits.length - 1]) {
207
+ case '1':
208
+ param = param + 'st';
171
209
  break;
172
- case 'x':
173
- case 'X':
174
- maybe_sign += "0x";
210
+ case '2':
211
+ param = param + 'nd';
175
212
  break;
176
- case 'b':
177
- maybe_sign += "0b";
213
+ case '3':
214
+ param = param + 'rd';
178
215
  break;
216
+ default: param = param + 'th';
179
217
  }
180
- }
181
- //pad with zeroes if specified
182
- if ($pad_zeroes === '0') {
183
- filled = true;
184
- while (param.length < width - maybe_sign.length) {
185
- param = '0' + param;
186
- true_length++;
187
- }
188
- }
189
- true_length += maybe_sign.length;
190
- param = maybe_sign + param;
191
- }
192
- if (!filled && width > true_length) {
193
- // Compute fill/align
194
- $align_direction ||= '>';
195
- $fill_character ||= ' ';
196
- let left = '';
197
- let right = '';
198
- let diff = width - true_length;
199
- switch ($align_direction) {
200
- case '>':
201
- left = $fill_character.repeat(diff);
218
+ if (format.type == 'N')
219
+ param = param.toUpperCase();
220
+ // Do not pad with zeroes or align to precision when using ordinal formatting
221
+ format.pad_zeroes = false;
222
+ format.precision = -1;
223
+ break;
224
+ case '?':
225
+ param = node_util_1.default.inspect(param, {
226
+ depth: Infinity,
227
+ colors: true,
228
+ compact: !format.pretty
229
+ });
230
+ // Do not force sign, pad with zeroes or align to precision when using debug formatting
231
+ param_type = 'string';
232
+ break;
233
+ default:
234
+ param = param.toString();
235
+ break;
236
+ }
237
+ ;
238
+ // Compute radix-point precision on numbers
239
+ if (param_type == 'number' && format.precision != -1) {
240
+ let [pre, post] = param.split('.');
241
+ if (!format.precision) { // precision = 0, do not include radix point
242
+ param = pre;
243
+ }
244
+ else {
245
+ post = ((post || '') + '0'.repeat(format.precision)).slice(0, format.precision);
246
+ param = pre + '.' + post;
247
+ }
248
+ }
249
+ // let filled = false;
250
+ if ((param_type == 'number') || (param_type == 'bigint')) {
251
+ // Compute parameter sign
252
+ let maybe_sign = param.substring(0, 1);
253
+ if (maybe_sign === '-') {
254
+ param = param.substring(1, param.length);
255
+ }
256
+ else if (format.force_sign == '+') {
257
+ maybe_sign = '+';
258
+ }
259
+ else if (format.force_sign == '-') {
260
+ maybe_sign = ' ';
261
+ }
262
+ else {
263
+ maybe_sign = '';
264
+ }
265
+ // If pretty printing is enabled and the formating calls for a prefix, add it
266
+ if (format.pretty) {
267
+ switch (format.type) {
268
+ case 'o':
269
+ maybe_sign += '0o';
202
270
  break;
203
- case '<':
204
- right = $fill_character.repeat(diff);
271
+ case 'x':
272
+ case 'X':
273
+ maybe_sign += '0x';
205
274
  break;
206
- case '^':
207
- left = $fill_character.repeat(diff - diff / 2);
208
- // Prioritise right-aligment on uneven length
209
- right = $fill_character.repeat(diff / 2 + diff % 2);
275
+ case 'b':
276
+ maybe_sign += '0b';
210
277
  break;
211
278
  }
212
- param = left + param + right;
213
279
  }
214
- return param;
215
- });
216
- return str;
280
+ //pad with zeroes if specified
281
+ if (format.pad_zeroes) {
282
+ // filled = true;
283
+ while (param.length < format.width - maybe_sign.length) {
284
+ param = '0' + param;
285
+ }
286
+ }
287
+ param = maybe_sign + param;
288
+ }
289
+ if ( /*!filled && */format.width > param.length) {
290
+ // Compute fill/align
291
+ let left = '';
292
+ let right = '';
293
+ let diff = format.width - param.length;
294
+ switch (format.align) {
295
+ case '>':
296
+ left = format.fill.repeat(diff);
297
+ break;
298
+ case '<':
299
+ right = format.fill.repeat(diff);
300
+ break;
301
+ case '^':
302
+ left = format.fill.repeat(diff - diff / 2);
303
+ // Prioritise right-aligment on uneven length
304
+ right = format.fill.repeat(diff / 2 + diff % 2);
305
+ break;
306
+ }
307
+ param = left + param + right;
308
+ }
309
+ return param;
217
310
  }
218
- exports.fmt_raw = fmt_raw;
311
+ exports.formatParam = formatParam;
package/lib/index.d.ts CHANGED
@@ -1,2 +1,15 @@
1
- export { format } from './format';
1
+ import { RsString } from './format';
2
2
  export { print, println, eprint, eprintln } from './print';
3
+ /**
4
+ * Tag to use Rust-style formatting in a template literal.
5
+ * Returns an extended `String` object.
6
+ *
7
+ * @returns a String object with the formatted string
8
+ */
9
+ export declare function rs(strings: TemplateStringsArray, ...params: any[]): RsString;
10
+ export declare namespace rs {
11
+ var raw: (strings: TemplateStringsArray, ...params: any[]) => string;
12
+ var ref: (n: number) => {
13
+ __rs_param_ref: number;
14
+ };
15
+ }
package/lib/index.js CHANGED
@@ -1,10 +1,35 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.eprintln = exports.eprint = exports.println = exports.print = exports.format = void 0;
4
- var format_1 = require("./format");
5
- Object.defineProperty(exports, "format", { enumerable: true, get: function () { return format_1.format; } });
3
+ exports.rs = exports.eprintln = exports.eprint = exports.println = exports.print = void 0;
4
+ const format_1 = require("./format");
6
5
  var print_1 = require("./print");
7
6
  Object.defineProperty(exports, "print", { enumerable: true, get: function () { return print_1.print; } });
8
7
  Object.defineProperty(exports, "println", { enumerable: true, get: function () { return print_1.println; } });
9
8
  Object.defineProperty(exports, "eprint", { enumerable: true, get: function () { return print_1.eprint; } });
10
9
  Object.defineProperty(exports, "eprintln", { enumerable: true, get: function () { return print_1.eprintln; } });
10
+ /**
11
+ * Tag to use Rust-style formatting in a template literal.
12
+ * Returns an extended `String` object.
13
+ *
14
+ * @returns a String object with the formatted string
15
+ */
16
+ function rs(strings, ...params) {
17
+ return new format_1.RsString(strings, params);
18
+ }
19
+ exports.rs = rs;
20
+ /**
21
+ * Tag to use Rust-style formatting in a template literal.
22
+ * Returns a `string` primitive.
23
+ *
24
+ * @returns a string primitive of the formatted string
25
+ */
26
+ rs.raw = function (strings, ...params) {
27
+ return (0, format_1.buildString)(strings, params).raw;
28
+ };
29
+ /**
30
+ * Reference another parameter in a `rs`-tagged template.
31
+ *
32
+ * @param n Number of parameter to reference
33
+ * @returns A reference to the `n`th parameter
34
+ */
35
+ rs.ref = (n) => ({ __rs_param_ref: n });
package/lib/print.d.ts CHANGED
@@ -1,75 +1,41 @@
1
1
  /// <reference types="node" />
2
2
  import { Writable } from 'node:stream';
3
3
  /**
4
- * Create format printer functions with custom output/error streams.
4
+ * Print a string (or instance of String/RsString) to a stream.
5
5
  *
6
- * @param outStream Output stream (used by print and println - process.stdout by default)
7
- * @param errStream Error stream (used by eprint and eprintln - process.stderr by default)
8
- * @param options Options for the printer functions (Whether to color the debug formatting in the output - true by default)
6
+ * @param stream Stream to print the string to
7
+ * @param string String to print
8
+ * @param newline Whether to append a newline after the string
9
+ * @param colored Whether to use colors for `rs` debug formatting
10
+ */
11
+ export declare function printToStream(stream: Writable, string: string | String, newline?: boolean, colored?: boolean): void;
12
+ /**
13
+ * Print a string to stdout.
9
14
  *
10
- * @returns an object with print, println, eprint and eprintln functions that print to the specified streams
15
+ * @param string String to print
11
16
  */
12
- export declare function Printer(outStream?: Writable, errStream?: Writable, options?: {
13
- debugColors: boolean;
14
- }): {
15
- /**
16
- * Print a format string to an output stream (usually process.stdout).
17
- *
18
- * @param format_string String used for formatting
19
- * @param params Parameters to be inserted into the format string
20
- */
21
- print: (format_string: string, ...params: any[]) => void;
22
- /**
23
- * Print a format string to an output stream (usually process.stdout)
24
- * and append a newline.
25
- *
26
- * @param format_string String used for formatting
27
- * @param params Parameters to be inserted into the format string
28
- */
29
- println: (format_string: string, ...params: any[]) => void;
30
- /**
31
- * Print a format string to an error stream (usually process.stderr).
32
- *
33
- * @param format_string String used for formatting
34
- * @param params Parameters to be inserted into the format string
35
- */
36
- eprint: (format_string: string, ...params: any[]) => void;
37
- /**
38
- * Print a format string to an error stream (usually process.stderr)
39
- * and append a newline.
40
- *
41
- * @param format_string String used for formatting
42
- * @param params Parameters to be inserted into the format string
43
- */
44
- eprintln: (format_string: string, ...params: any[]) => void;
45
- };
17
+ export declare function print(string: string | String): void;
46
18
  /**
47
- * Print a format string to process.stdout.
19
+ * Print a string to stdout and append a newline.
48
20
  *
49
- * @param format_string String used for formatting
50
- * @param params Parameters to be inserted into the format string
21
+ * @param string String to print
51
22
  */
52
- export declare const print: (format_string: string, ...params: any[]) => void;
23
+ export declare function println(string: string | String): void;
53
24
  /**
54
- * Print a format string to process.stdout
55
- * and append a newline.
25
+ * Print a string to stderr.
56
26
  *
57
- * @param format_string String used for formatting
58
- * @param params Parameters to be inserted into the format string
27
+ * @param string String to print
59
28
  */
60
- export declare const println: (format_string: string, ...params: any[]) => void;
29
+ export declare function eprint(string: string | String): void;
61
30
  /**
62
- * Print a format string to process.stderr.
31
+ * Print a string to stderr and append a newline.
63
32
  *
64
- * @param format_string String used for formatting
65
- * @param params Parameters to be inserted into the format string
33
+ * @param string String to print
66
34
  */
67
- export declare const eprint: (format_string: string, ...params: any[]) => void;
35
+ export declare function eprintln(string: string | String): void;
68
36
  /**
69
- * Print a format string to process.stderr
70
- * and append a newline.
37
+ * Debug print a value to stderr and return it.
71
38
  *
72
- * @param format_string String used for formatting
73
- * @param params Parameters to be inserted into the format string
39
+ * @param value Value to debug print
74
40
  */
75
- export declare const eprintln: (format_string: string, ...params: any[]) => void;
41
+ export declare function dbg(value: any): any;
package/lib/print.js CHANGED
@@ -3,89 +3,69 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.eprintln = exports.eprint = exports.println = exports.print = exports.Printer = void 0;
6
+ exports.dbg = exports.eprintln = exports.eprint = exports.println = exports.print = exports.printToStream = void 0;
7
7
  const node_process_1 = __importDefault(require("node:process"));
8
- const format_1 = require("./format");
8
+ const _1 = require(".");
9
9
  /**
10
- * Create format printer functions with custom output/error streams.
10
+ * Print a string (or instance of String/RsString) to a stream.
11
11
  *
12
- * @param outStream Output stream (used by print and println - process.stdout by default)
13
- * @param errStream Error stream (used by eprint and eprintln - process.stderr by default)
14
- * @param options Options for the printer functions (Whether to color the debug formatting in the output - true by default)
12
+ * @param stream Stream to print the string to
13
+ * @param string String to print
14
+ * @param newline Whether to append a newline after the string
15
+ * @param colored Whether to use colors for `rs` debug formatting
16
+ */
17
+ function printToStream(stream, string, newline = false, colored = false) {
18
+ if (string instanceof String) {
19
+ string = string.toString(true);
20
+ }
21
+ if (newline)
22
+ string = string + '\n';
23
+ stream.write(string);
24
+ }
25
+ exports.printToStream = printToStream;
26
+ /**
27
+ * Print a string to stdout.
15
28
  *
16
- * @returns an object with print, println, eprint and eprintln functions that print to the specified streams
29
+ * @param string String to print
17
30
  */
18
- function Printer(outStream = node_process_1.default.stdout, errStream = node_process_1.default.stderr, options = { debugColors: true }) {
19
- return {
20
- /**
21
- * Print a format string to an output stream (usually process.stdout).
22
- *
23
- * @param format_string String used for formatting
24
- * @param params Parameters to be inserted into the format string
25
- */
26
- print: function print(format_string, ...params) {
27
- outStream.write((0, format_1.fmt_raw)(format_string, params, { colors: options.debugColors }));
28
- },
29
- /**
30
- * Print a format string to an output stream (usually process.stdout)
31
- * and append a newline.
32
- *
33
- * @param format_string String used for formatting
34
- * @param params Parameters to be inserted into the format string
35
- */
36
- println: function println(format_string, ...params) {
37
- outStream.write((0, format_1.fmt_raw)(format_string, params, { colors: options.debugColors }) + '\n');
38
- },
39
- /**
40
- * Print a format string to an error stream (usually process.stderr).
41
- *
42
- * @param format_string String used for formatting
43
- * @param params Parameters to be inserted into the format string
44
- */
45
- eprint: function eprint(format_string, ...params) {
46
- errStream.write((0, format_1.fmt_raw)(format_string, params, { colors: options.debugColors }));
47
- },
48
- /**
49
- * Print a format string to an error stream (usually process.stderr)
50
- * and append a newline.
51
- *
52
- * @param format_string String used for formatting
53
- * @param params Parameters to be inserted into the format string
54
- */
55
- eprintln: function eprintln(format_string, ...params) {
56
- errStream.write((0, format_1.fmt_raw)(format_string, params, { colors: options.debugColors }) + '\n');
57
- },
58
- };
31
+ function print(string) {
32
+ printToStream(node_process_1.default.stdout, string, false, true);
59
33
  }
60
- exports.Printer = Printer;
61
- const default_printer = Printer();
34
+ exports.print = print;
62
35
  /**
63
- * Print a format string to process.stdout.
36
+ * Print a string to stdout and append a newline.
64
37
  *
65
- * @param format_string String used for formatting
66
- * @param params Parameters to be inserted into the format string
38
+ * @param string String to print
67
39
  */
68
- exports.print = default_printer.print;
40
+ function println(string) {
41
+ printToStream(node_process_1.default.stdout, string, true, true);
42
+ }
43
+ exports.println = println;
69
44
  /**
70
- * Print a format string to process.stdout
71
- * and append a newline.
45
+ * Print a string to stderr.
72
46
  *
73
- * @param format_string String used for formatting
74
- * @param params Parameters to be inserted into the format string
47
+ * @param string String to print
75
48
  */
76
- exports.println = default_printer.println;
49
+ function eprint(string) {
50
+ printToStream(node_process_1.default.stderr, string, false, true);
51
+ }
52
+ exports.eprint = eprint;
77
53
  /**
78
- * Print a format string to process.stderr.
54
+ * Print a string to stderr and append a newline.
79
55
  *
80
- * @param format_string String used for formatting
81
- * @param params Parameters to be inserted into the format string
56
+ * @param string String to print
82
57
  */
83
- exports.eprint = default_printer.eprint;
58
+ function eprintln(string) {
59
+ printToStream(node_process_1.default.stderr, string, true, true);
60
+ }
61
+ exports.eprintln = eprintln;
84
62
  /**
85
- * Print a format string to process.stderr
86
- * and append a newline.
63
+ * Debug print a value to stderr and return it.
87
64
  *
88
- * @param format_string String used for formatting
89
- * @param params Parameters to be inserted into the format string
65
+ * @param value Value to debug print
90
66
  */
91
- exports.eprintln = default_printer.eprintln;
67
+ function dbg(value) {
68
+ eprintln((0, _1.rs) `${value}:?`);
69
+ return value;
70
+ }
71
+ exports.dbg = dbg;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rsformat",
3
- "version": "0.2.5",
3
+ "version": "1.1.0",
4
4
  "description": "Formatting/printing library for JavaScript that takes after rust's string formatting ",
5
5
  "files": [
6
6
  "lib",