Skip to content

Commit 15bf50a

Browse files
Planeshifterstdlib-botkgryte
authored
Add utility to parse duration string into ms (stdlib-js#561)
* Add utility to parse duration string into ms * Scaffold time/duration2ms package files * Clean-up scaffolded files * Finish implementation and clean-up * Fix spelling * Use a lighter weight check * Fix spelling * Fix formatting * Fix spelling * Fix spelling * Fix error message formatting * Update description and incorporate suggestions * Update check * Add missing shebang Co-authored-by: stdlib-bot <noreply@stdlib.io> Co-authored-by: Athan <kgryte@gmail.com>
1 parent 2dc7cfb commit 15bf50a

File tree

15 files changed

+1187
-0
lines changed

15 files changed

+1187
-0
lines changed
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2022 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# duration2ms
22+
23+
> Convert a duration string to milliseconds.
24+
25+
<section class="usage">
26+
27+
## Usage
28+
29+
```javascript
30+
var duration2ms = require( '@stdlib/time/duration2ms' );
31+
```
32+
33+
#### duration2ms( str )
34+
35+
Converts a duration string to milliseconds.
36+
37+
```javascript
38+
var ms = duration2ms( '1d' );
39+
// returns 86400000
40+
41+
ms = duration2ms( '1d2h3m4s5ms' );
42+
// returns 93784005
43+
```
44+
45+
</section>
46+
47+
<!-- /.usage -->
48+
49+
<section class="notes">
50+
51+
## Notes
52+
53+
- A duration string is a string containing a sequence of time units. A time unit is a nonnegative integer followed by a unit identifier. The following unit identifiers are supported:
54+
55+
- `d`: days
56+
- `h`: hours
57+
- `m`: minutes
58+
- `s`: seconds
59+
- `ms`: milliseconds
60+
61+
For example, the string `1m3s10ms` is a duration string containing three time units: `1m` (1 minute), `3s` (3 seconds), and `10ms` (10 milliseconds). The string `60m` is a duration string containing a single time unit: `60m` (60 minutes).
62+
63+
- Duration strings are case insensitive. For example, the string `1M3S10MS` is equivalent to `1m3s10ms`.
64+
65+
</section>
66+
67+
<!-- /.notes -->
68+
69+
<section class="examples">
70+
71+
## Examples
72+
73+
<!-- eslint no-undef: "error" -->
74+
75+
```javascript
76+
var duration2ms = require( '@stdlib/time/duration2ms' );
77+
78+
var ms = duration2ms( '5s20ms' );
79+
// returns 5020
80+
81+
ms = duration2ms( '1h' );
82+
// returns 3600000
83+
84+
ms = duration2ms( '1m2s3ms' );
85+
// returns 62003
86+
```
87+
88+
</section>
89+
90+
<!-- /.examples -->
91+
92+
* * *
93+
94+
<section class="cli">
95+
96+
## CLI
97+
98+
<section class="usage">
99+
100+
### Usage
101+
102+
```text
103+
Usage: duration2ms [options] [<string>]
104+
105+
Options:
106+
107+
-h, --help Print this message.
108+
-V, --version Print the package version.
109+
--split sep Delimiter for stdin data. Default: '/\\r?\\n/'.
110+
```
111+
112+
</section>
113+
114+
<!-- /.usage -->
115+
116+
<!-- CLI usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
117+
118+
<section class="notes">
119+
120+
### Notes
121+
122+
- If the split separator is a [regular expression][mdn-regexp], ensure that the `split` option is either properly escaped or enclosed in quotes.
123+
124+
```bash
125+
# Not escaped...
126+
$ echo -n $'3s\n5s20ms' | duration2ms --split /\r?\n/
127+
128+
# Escaped...
129+
$ echo -n $'3s\n5s20ms' | duration2ms --split /\\r?\\n/
130+
```
131+
132+
- The implementation ignores trailing delimiters.
133+
134+
</section>
135+
136+
<!-- /.notes -->
137+
138+
<section class="examples">
139+
140+
### Examples
141+
142+
```bash
143+
$ duration2ms 1s
144+
1000
145+
```
146+
147+
To use as a [standard stream][standard-streams],
148+
149+
```bash
150+
$ echo -n '1s\n2s' | duration2ms
151+
1000
152+
2000
153+
```
154+
155+
By default, when used as a [standard stream][standard-streams], the implementation assumes newline-delimited data. To specify an alternative delimiter, set the `split` option.
156+
157+
```bash
158+
$ echo -n '1s350ms,2s' | duration2ms --split ','
159+
1350
160+
2000
161+
```
162+
163+
</section>
164+
165+
<!-- /.examples -->
166+
167+
</section>
168+
169+
<!-- /.cli -->
170+
171+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
172+
173+
<section class="related">
174+
175+
<!-- /.related -->
176+
177+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
178+
179+
<section class="links">
180+
181+
[standard-streams]: https://en.wikipedia.org/wiki/Standard_streams
182+
183+
[mdn-regexp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
184+
185+
<!-- <related-links> -->
186+
187+
<!-- </related-links> -->
188+
189+
</section>
190+
191+
<!-- /.links -->
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2022 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
25+
var pkg = require( './../package.json' ).name;
26+
var duration2ms = require( './../lib' );
27+
28+
29+
// MAIN //
30+
31+
bench( pkg, function benchmark( b ) {
32+
var values;
33+
var ms;
34+
var i;
35+
36+
values = [
37+
'1d',
38+
'1d2h3m4s5ms',
39+
'1d2h3m4s',
40+
'1d2h3m',
41+
'1d2h',
42+
'1d2m',
43+
'1d2s5ms',
44+
'1d2s',
45+
'1d5ms',
46+
'1d',
47+
'1h3m4s5ms',
48+
'1h3m4s',
49+
'1h3m',
50+
'1h2m',
51+
'1h2s5ms',
52+
'1h2s',
53+
'1h5ms',
54+
'1h',
55+
'1m4s5ms',
56+
'1m4s',
57+
'1m',
58+
'1s5ms',
59+
'1s',
60+
'5ms',
61+
'1ms'
62+
];
63+
64+
b.tic();
65+
for ( i = 0; i < b.iterations; i++ ) {
66+
ms = duration2ms( values[ i % values.length ] );
67+
if ( ms !== ms ) {
68+
b.fail( 'should not return NaN' );
69+
}
70+
}
71+
b.toc();
72+
if ( !isInteger( ms ) ) {
73+
b.fail( 'should return an integer' );
74+
}
75+
b.pass( 'benchmark finished' );
76+
b.end();
77+
});
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* @license Apache-2.0
5+
*
6+
* Copyright (c) 2022 The Stdlib Authors.
7+
*
8+
* Licensed under the Apache License, Version 2.0 (the "License");
9+
* you may not use this file except in compliance with the License.
10+
* You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing, software
15+
* distributed under the License is distributed on an "AS IS" BASIS,
16+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
* See the License for the specific language governing permissions and
18+
* limitations under the License.
19+
*/
20+
21+
'use strict';
22+
23+
// MODULES //
24+
25+
var resolve = require( 'path' ).resolve;
26+
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
27+
var CLI = require( '@stdlib/cli/ctor' );
28+
var stdin = require( '@stdlib/process/read-stdin' );
29+
var stdinStream = require( '@stdlib/streams/node/stdin' );
30+
var RE_EOL = require( '@stdlib/regexp/eol' ).REGEXP;
31+
var isRegExpString = require( '@stdlib/assert/is-regexp-string' );
32+
var reFromString = require( '@stdlib/utils/regexp-from-string' );
33+
var duration2ms = require( './../lib' );
34+
35+
36+
// MAIN //
37+
38+
/**
39+
* Main execution sequence.
40+
*
41+
* @private
42+
* @returns {void}
43+
*/
44+
function main() {
45+
var split;
46+
var flags;
47+
var args;
48+
var cli;
49+
50+
// Create a command-line interface:
51+
cli = new CLI({
52+
'pkg': require( './../package.json' ),
53+
'options': require( './../etc/cli_opts.json' ),
54+
'help': readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
55+
'encoding': 'utf8'
56+
})
57+
});
58+
59+
// Get any provided command-line options:
60+
flags = cli.flags();
61+
if ( flags.help || flags.version ) {
62+
return;
63+
}
64+
65+
// Get any provided command-line arguments:
66+
args = cli.args();
67+
68+
// Check if we are receiving data from `stdin`...
69+
if ( !stdinStream.isTTY ) {
70+
if ( flags.split ) {
71+
if ( !isRegExpString( flags.split ) ) {
72+
flags.split = '/'+flags.split+'/';
73+
}
74+
split = reFromString( flags.split );
75+
} else {
76+
split = RE_EOL;
77+
}
78+
return stdin( onRead );
79+
}
80+
console.log( duration2ms( args[ 0 ] ) ); // eslint-disable-line no-console
81+
82+
/**
83+
* Callback invoked upon reading from `stdin`.
84+
*
85+
* @private
86+
* @param {(Error|null)} error - error object
87+
* @param {Buffer} data - data
88+
* @returns {void}
89+
*/
90+
function onRead( error, data ) {
91+
var lines;
92+
var i;
93+
if ( error ) {
94+
return cli.error( error );
95+
}
96+
lines = data.toString().split( split );
97+
98+
// Remove any trailing separators (e.g., trailing newline)...
99+
if ( lines[ lines.length-1 ] === '' ) {
100+
lines.pop();
101+
}
102+
for ( i = 0; i < lines.length; i++ ) {
103+
console.log( duration2ms( lines[ i ] ) ); // eslint-disable-line no-console
104+
}
105+
}
106+
}
107+
108+
main();

0 commit comments

Comments
 (0)