Skip to content

Commit 094bbe4

Browse files
committed
Add precision property, handle invalid duration strings
1 parent 49567bc commit 094bbe4

File tree

4 files changed

+42
-6
lines changed

4 files changed

+42
-6
lines changed

.babelrc

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"presets" : [
3+
"babel-preset-es2015"
4+
],
5+
"plugins": [
6+
"syntax-trailing-function-commas"
7+
]
8+
}

package.json

+4-3
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
"test": "test"
88
},
99
"scripts": {
10-
"build": "babel --quiet --presets es2015 source --out-dir build",
11-
"test": "npm run build && ava --fail-fast",
12-
"prepublish": "npm test"
10+
"build": "babel --quiet source --out-dir build",
11+
"test": "ava --require babel-register --fail-fast",
12+
"prepublish": "npm test && npm run build"
1313
},
1414
"keywords": [
1515
"duration",
@@ -21,6 +21,7 @@
2121
"ava": "^0.12.0",
2222
"babel-cli": "^6.6.5",
2323
"babel-preset-es2015": "^6.6.0",
24+
"babel-register": "^6.6.5",
2425
"unexpected": "^10.4.0"
2526
},
2627
"repository": {

source/index.js

+17-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import durationFragments from './fragments'
33
export default class Duration {
44
constructor (durationString) {
55
let durationPattern =
6-
'P' +
6+
'^P' +
77
'(?:(\\d+)Y)?' + // Years
88
'(?:(\\d+)M)?' + // Months
99
'(?:(\\d+)W)?' + // Weeks
@@ -12,18 +12,32 @@ export default class Duration {
1212
'(?:(\\d+)H)?' + // Hours
1313
'(?:(\\d+)M)?' + // Minutes
1414
'(?:(\\d+)?' + // Seconds
15-
'\\.?(\\d+)?S)?' // Milliseconds
15+
'\\.?(\\d+)?S)?' + // Milliseconds
16+
'$'
1617

1718
let regex = new RegExp(durationPattern, 'i')
1819
let durationArray = durationString.match(regex)
1920

21+
if (!durationArray) {
22+
throw new Error(`"${durationString}" is an invalid duration string`)
23+
}
24+
2025
durationFragments.forEach((fragment, index) => {
2126
let value = Number(durationArray[index + 1])
22-
if (value)
27+
28+
if (typeof value === 'number' && !Number.isNaN(value)) {
29+
this._precision = fragment.replace('s', '')
2330
this[fragment] = value
31+
}
2432
})
2533
}
2634

35+
get precision () { return this._precision }
36+
set precision (precision) {
37+
this._precision = precision
38+
return this
39+
}
40+
2741
get string () {
2842
return durationFragments
2943
.reduce(

test/precision.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import runTest from 'ava'
2+
import expect from 'unexpected'
3+
import Duration from '../source/index.js'
4+
5+
runTest('precision of P7D is day', test => {
6+
const duration = new Duration('P7D')
7+
expect(duration.precision, 'to equal', 'day')
8+
})
9+
10+
runTest('precision of P7D0H is hour', test => {
11+
const duration = new Duration('P7D0H')
12+
expect(duration.precision, 'to equal', 'hour')
13+
})

0 commit comments

Comments
 (0)