Skip to content

Commit 25fb38c

Browse files
committed
adjust initial unit
1 parent fc1a988 commit 25fb38c

1 file changed

Lines changed: 43 additions & 10 deletions

File tree

src/components/fields/BinSize.js

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,40 @@ const MILLISECONDS_IN_MINUTE = MILLISECONDS_IN_SECOND * 60; // eslint-disable-li
1212
const MILLISECONDS_IN_DAY = MILLISECONDS_IN_MINUTE * 60 * 24; // eslint-disable-line
1313
const DAYS_IN_MONTH = 30;
1414

15+
function getSmallestUnit(milliseconds) {
16+
const units = {
17+
seconds: MILLISECONDS_IN_SECOND,
18+
minutes: MILLISECONDS_IN_MINUTE,
19+
days: MILLISECONDS_IN_DAY,
20+
};
21+
22+
let smallestUnit = 'milliseconds';
23+
24+
['seconds', 'minutes', 'days'].forEach(unit => {
25+
if (
26+
milliseconds % units[unit] === 0 &&
27+
(smallestUnit === 'milliseconds' ||
28+
(smallestUnit !== 'milliseconds' &&
29+
milliseconds / units[smallestUnit] > milliseconds / units[unit]))
30+
) {
31+
smallestUnit = unit;
32+
}
33+
});
34+
35+
return smallestUnit;
36+
}
37+
1538
class UnconnectedBinSize extends Component {
16-
constructor() {
17-
super();
39+
constructor(props) {
40+
super(props);
41+
42+
const initialUnit =
43+
props.fullValue && typeof props.fullValue === 'string' && props.fullValue[0] === 'M'
44+
? 'months'
45+
: getSmallestUnit(props.fullValue);
46+
1847
this.state = {
19-
units: 'months',
48+
units: initialUnit,
2049
};
2150
}
2251

@@ -35,7 +64,7 @@ class UnconnectedBinSize extends Component {
3564
adjustedValue = adjustedValue * MILLISECONDS_IN_MINUTE;
3665
}
3766

38-
if (this.state.seconds === 'seconds') {
67+
if (this.state.units === 'seconds') {
3968
adjustedValue = adjustedValue * MILLISECONDS_IN_SECOND;
4069
}
4170

@@ -59,20 +88,24 @@ class UnconnectedBinSize extends Component {
5988
}
6089

6190
getDisplayValue(value) {
62-
if (this.state.units === 'months' && typeof value === 'string' && value[0] === 'M') {
63-
return parseInt(value.substring(1), 10);
91+
const numericValue =
92+
typeof value === 'string' && value[0] === 'M' ? parseInt(value.substring(1), 10) : value;
93+
94+
if (this.state.units === 'months') {
95+
return numericValue;
6496
}
97+
6598
if (this.state.units === 'days') {
66-
return Math.round(value / MILLISECONDS_IN_DAY);
99+
return Math.round(numericValue / MILLISECONDS_IN_DAY);
67100
}
68101
if (this.state.units === 'minutes') {
69-
return Math.round(value / MILLISECONDS_IN_MINUTE);
102+
return Math.round(numericValue / MILLISECONDS_IN_MINUTE);
70103
}
71104
if (this.state.units === 'seconds') {
72-
return Math.round(value / MILLISECONDS_IN_SECOND);
105+
return Math.round(numericValue / MILLISECONDS_IN_SECOND);
73106
}
74107
if (this.state.units === 'milliseconds') {
75-
return value;
108+
return numericValue;
76109
}
77110
return null;
78111
}

0 commit comments

Comments
 (0)