rsformat 0.2.4 → 0.2.5

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
@@ -1,170 +1,170 @@
1
- # RSFormat
2
-
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
-
5
- ## Motivation
6
-
7
- `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
-
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.
10
-
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.
12
-
13
- ## Usage
14
-
15
- you can install rsformat using [npm](https://www.npmjs.com/package/rsformat):
16
-
17
- ```
18
- npm install rsformat
19
- ```
20
-
21
- ### Basic formatting and printing to console
22
-
23
- RSFormat functions are called using a format string, and any number of format arguments following it.
24
-
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.
28
-
29
- ```js
30
- import { format, println } from 'rsformat'; // ESM
31
- const { format, println } = require('rsformat'); // CommonJS
32
-
33
- let name = 'everyone';
34
-
35
- let greeting = format('Hello {}!', name); // Evaluates to the string 'Hello, everyone!'
36
-
37
- println('I have {1} apples and {0} oranges', 13, 14); // Will print 'I have 14 apples and 13 oranges' to the console
38
- ```
39
-
40
- ### Format Specifiers
41
-
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.
43
-
44
- This implementation differs from the rust one in a few ways:
45
-
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.
48
- - Pointer format type `p` is unsupported.
49
- - Hexadecimal debug types `x?` and `X?` are unsupported.
50
- - Specifying precision with `*` is unsupported.
51
-
52
- #### Different formatting types
53
-
54
- ```js
55
- // Debug format specifier: ?, uses util.inspect rather than toString
56
-
57
- println('{}', { a: 1 }); //prints '[object Object]'
58
- println('{:?}', { a: 1 }); //prints "{ a:1 }"
59
-
60
- // Number base specifiers: x, X, b, o - for lower/uppercase hexadecimal, binary, octal
61
-
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'
63
-
64
- // Scientific notation specifiers: e, E - for lower/uppercase scientific notation
65
-
66
- let hugeNumber = 1000n;
67
- format('{:E}', hugeNumber); // '1E3';
68
- ```
69
-
70
- #### Padding, Alignment
71
-
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:
73
-
74
- ```js
75
- /*
76
- Will print a pyramid of 'a's:
77
- ' a '
78
- ' aaa '
79
- 'aaaaa'
80
- */
81
- let pyramidLevels = ['a', 'aaa', 'aaaaa'];
82
- for(let value of pyramidLevels) {
83
- println('{:^5}', value);
84
- }
85
- ```
86
-
87
- ```js
88
- format('{:.>7}', [1,2]); // '....1,2'
89
- ```
90
-
91
- #### Pretty Printing
92
-
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.
94
-
95
- ```js
96
- format('{:#X}', 255); // '0xFF'
97
- ```
98
-
99
- #### Specific Number Formatting
100
-
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.
102
-
103
- ```js
104
- format('{:#07x}', 15) // '0x0000F'
105
- ```
106
-
107
- Decimal precision can be specified for numbers by adding a . and specifying an integer for precision.
108
-
109
- ```js
110
- format('{:.3}', 1.23456789); // '1.234'
111
- format('{:.3}', -1); // '-1.000'
112
- ```
113
-
114
- Adding a + to the formatting specifier will print the sign regardless of whether the number is negative.
115
-
116
- ```js
117
- format('{:+}', 1); // '+1'
118
- ```
119
-
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`.
123
-
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:
140
-
141
- ```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
168
- ```
169
-
1
+ # RSFormat
2
+
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
+
5
+ ## Motivation
6
+
7
+ `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
+
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.
10
+
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.
12
+
13
+ ## Usage
14
+
15
+ you can install rsformat using [npm](https://www.npmjs.com/package/rsformat):
16
+
17
+ ```
18
+ npm install rsformat
19
+ ```
20
+
21
+ ### Basic formatting and printing to console
22
+
23
+ RSFormat functions are called using a format string, and any number of format arguments following it.
24
+
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.
28
+
29
+ ```js
30
+ import { format, println } from 'rsformat'; // ESM
31
+ const { format, println } = require('rsformat'); // CommonJS
32
+
33
+ let name = 'everyone';
34
+
35
+ let greeting = format('Hello {}!', name); // Evaluates to the string 'Hello, everyone!'
36
+
37
+ println('I have {1} apples and {0} oranges', 13, 14); // Will print 'I have 14 apples and 13 oranges' to the console
38
+ ```
39
+
40
+ ### Format Specifiers
41
+
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.
43
+
44
+ This implementation differs from the rust one in a few ways:
45
+
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.
48
+ - Pointer format type `p` is unsupported.
49
+ - Hexadecimal debug types `x?` and `X?` are unsupported.
50
+ - Specifying precision with `*` is unsupported.
51
+
52
+ #### Different formatting types
53
+
54
+ ```js
55
+ // Debug format specifier: ?, uses util.inspect rather than toString
56
+
57
+ println('{}', { a: 1 }); //prints '[object Object]'
58
+ println('{:?}', { a: 1 }); //prints "{ a:1 }"
59
+
60
+ // Number base specifiers: x, X, b, o - for lower/uppercase hexadecimal, binary, octal
61
+
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'
63
+
64
+ // Scientific notation specifiers: e, E - for lower/uppercase scientific notation
65
+
66
+ let hugeNumber = 1000n;
67
+ format('{:E}', hugeNumber); // '1E3';
68
+ ```
69
+
70
+ #### Padding, Alignment
71
+
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:
73
+
74
+ ```js
75
+ /*
76
+ Will print a pyramid of 'a's:
77
+ ' a '
78
+ ' aaa '
79
+ 'aaaaa'
80
+ */
81
+ let pyramidLevels = ['a', 'aaa', 'aaaaa'];
82
+ for(let value of pyramidLevels) {
83
+ println('{:^5}', value);
84
+ }
85
+ ```
86
+
87
+ ```js
88
+ format('{:.>7}', [1,2]); // '....1,2'
89
+ ```
90
+
91
+ #### Pretty Printing
92
+
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.
94
+
95
+ ```js
96
+ format('{:#X}', 255); // '0xFF'
97
+ ```
98
+
99
+ #### Specific Number Formatting
100
+
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.
102
+
103
+ ```js
104
+ format('{:#07x}', 15) // '0x0000F'
105
+ ```
106
+
107
+ Decimal precision can be specified for numbers by adding a . and specifying an integer for precision.
108
+
109
+ ```js
110
+ format('{:.3}', 1.23456789); // '1.234'
111
+ format('{:.3}', -1); // '-1.000'
112
+ ```
113
+
114
+ Adding a + to the formatting specifier will print the sign regardless of whether the number is negative.
115
+
116
+ ```js
117
+ format('{:+}', 1); // '+1'
118
+ ```
119
+
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`.
123
+
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:
140
+
141
+ ```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
168
+ ```
169
+
170
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._
package/lib/format.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.format = format;
4
- exports.fmt_raw = fmt_raw;
3
+ exports.fmt_raw = exports.format = void 0;
5
4
  const node_util_1 = require("node:util");
6
5
  /**
7
6
  * Regex to match for possible formatting insertion points.
@@ -30,6 +29,7 @@ const FORMAT_REGEX = (/\{{2}|\}{2}|\{(\d*?)(?::(?:(.?)(\^|>|<))?(\+)?(#)?(0)?(\d
30
29
  function format(str, ...params) {
31
30
  return fmt_raw(str, params);
32
31
  }
32
+ exports.format = format;
33
33
  /**
34
34
  * Raw formatting behaviour function called by `format` and printing functions.
35
35
  *
@@ -104,8 +104,9 @@ function fmt_raw(str, params, options = { colors: false }) {
104
104
  }
105
105
  break;
106
106
  case '?':
107
- // Do not force sign or align to precision when using inspect
107
+ // Do not force sign, pad with zeroes or align to precision when using debug formatting
108
108
  $sign = undefined;
109
+ $pad_zeroes = undefined;
109
110
  $precision = undefined;
110
111
  true_length = (0, node_util_1.inspect)(param, {
111
112
  depth: Infinity,
@@ -136,6 +137,8 @@ function fmt_raw(str, params, options = { colors: false }) {
136
137
  else {
137
138
  post = ((post || '') + '0'.repeat(precision)).slice(0, precision);
138
139
  param = pre + '.' + post;
140
+ // Update true length for fill/align
141
+ true_length = param.length;
139
142
  }
140
143
  }
141
144
  let width;
@@ -180,8 +183,10 @@ function fmt_raw(str, params, options = { colors: false }) {
180
183
  filled = true;
181
184
  while (param.length < width - maybe_sign.length) {
182
185
  param = '0' + param;
186
+ true_length++;
183
187
  }
184
188
  }
189
+ true_length += maybe_sign.length;
185
190
  param = maybe_sign + param;
186
191
  }
187
192
  if (!filled && width > true_length) {
@@ -210,3 +215,4 @@ function fmt_raw(str, params, options = { colors: false }) {
210
215
  });
211
216
  return str;
212
217
  }
218
+ exports.fmt_raw = fmt_raw;
package/lib/print.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" />
1
2
  import { Writable } from 'node:stream';
2
3
  /**
3
4
  * Create format printer functions with custom output/error streams.
package/lib/print.js CHANGED
@@ -3,8 +3,7 @@ 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 = void 0;
7
- exports.Printer = Printer;
6
+ exports.eprintln = exports.eprint = exports.println = exports.print = exports.Printer = void 0;
8
7
  const node_process_1 = __importDefault(require("node:process"));
9
8
  const format_1 = require("./format");
10
9
  /**
@@ -58,38 +57,7 @@ function Printer(outStream = node_process_1.default.stdout, errStream = node_pro
58
57
  },
59
58
  };
60
59
  }
61
- // export const {
62
- // /**
63
- // * Print a format string to process.stdout.
64
- // *
65
- // * @param format_string String used for formatting
66
- // * @param params Parameters to be inserted into the format string
67
- // */
68
- // print,
69
- // /**
70
- // * Print a format string to process.stdout
71
- // * and append a newline.
72
- // *
73
- // * @param format_string String used for formatting
74
- // * @param params Parameters to be inserted into the format string
75
- // */
76
- // println,
77
- // /**
78
- // * Print a format string to process.stderr.
79
- // *
80
- // * @param format_string String used for formatting
81
- // * @param params Parameters to be inserted into the format string
82
- // */
83
- // eprint,
84
- // /**
85
- // * Print a format string to process.stderr
86
- // * and append a newline.
87
- // *
88
- // * @param format_string String used for formatting
89
- // * @param params Parameters to be inserted into the format string
90
- // */
91
- // eprintln
92
- // } = Printer();
60
+ exports.Printer = Printer;
93
61
  const default_printer = Printer();
94
62
  /**
95
63
  * Print a format string to process.stdout.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rsformat",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Formatting/printing library for JavaScript that takes after rust's string formatting ",
5
5
  "files": [
6
6
  "lib",
@@ -16,10 +16,6 @@
16
16
  "default": "./lib/*.js"
17
17
  }
18
18
  },
19
- "scripts": {
20
- "build": "tsc",
21
- "test": "echo \"Error: no test specified\" && exit 1"
22
- },
23
19
  "keywords": [
24
20
  "fmt",
25
21
  "format",
@@ -36,5 +32,8 @@
36
32
  "devDependencies": {
37
33
  "@types/node": "^22.8.6"
38
34
  },
39
- "packageManager": "pnpm@9.14.2+sha512.6e2baf77d06b9362294152c851c4f278ede37ab1eba3a55fda317a4a17b209f4dbb973fb250a77abc463a341fcb1f17f17cfa24091c4eb319cda0d9b84278387"
35
+ "scripts": {
36
+ "build": "tsc",
37
+ "test": "echo \"Error: no test specified\" && exit 1"
38
+ }
40
39
  }