Skip to content

Commit 41780c5

Browse files
committed
Implicitly set precision through smallest set unit
1 parent 74c18bd commit 41780c5

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

source/index.js

+17-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ export default class Duration {
3737
let value = Number(durationArray[index + 1])
3838

3939
if (typeof value === 'number' && !Number.isNaN(value)) {
40-
this._precision = fragment.replace(/s$/, '')
4140
this[fragment] = value
4241
}
4342
})
@@ -79,7 +78,23 @@ export default class Duration {
7978
}
8079

8180

82-
get precision () { return this._precision }
81+
get precision () {
82+
let precision
83+
84+
// Clone array as .reverse() is in place
85+
Array.from(durationFragments)
86+
.reverse()
87+
.some(fragment => {
88+
const value = this[fragment]
89+
90+
if (typeof value === 'number' && !Number.isNaN(value)) {
91+
precision = fragment.replace(/s$/, '')
92+
return true
93+
}
94+
})
95+
96+
return precision
97+
}
8398
set precision (precision) {
8499
this._precision = precision
85100
return this

test/precision.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
import runTest from 'ava'
22
import expect from 'unexpected'
3-
import Duration from '../source/index.js'
3+
import Duration from '../source/index'
44

55
runTest('precision of P7D is day', test => {
66
const duration = new Duration('P7D')
77
expect(duration.precision, 'to equal', 'day')
88
})
99

10+
runTest('precision of P5Y is year', test => {
11+
const duration = new Duration('P5Y')
12+
expect(duration.precision, 'to equal', 'year')
13+
})
14+
1015
runTest('precision of P7D0H is hour', test => {
1116
const duration = new Duration('P7D0H')
1217
expect(duration.precision, 'to equal', 'hour')

0 commit comments

Comments
 (0)