Skip to content

Commit ef035df

Browse files
committed
Add time-segment
1 parent 5d476c7 commit ef035df

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

solutions/other/time-segment.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
### 时间分段
2+
3+
指定格式为`06:30``6:30`的时间起点和终点,以及每个时间段的长度(分钟),得到一个划分好的的数组
4+
5+
```javascript
6+
const timeSegment = (start, end, step) => {
7+
const res = []
8+
const zeroFill = (num) => {
9+
return num < 10 ? `0${num}` : `${num}`
10+
}
11+
const _segment = (start, end, step) => {
12+
let arr = start.split(':').concat(end.split(':'))
13+
arr = arr.map(item => parseInt(item))
14+
let temp = arr[1] + step
15+
let tempHour = Math.floor(temp / 60)
16+
let tempMis = temp % 60
17+
let hour = tempHour + arr[0]
18+
if (arr[0] > arr[2] || arr[0] === arr[2] && arr[1] >= arr[3]) {
19+
if (hour >= 24) {
20+
hour -= 24
21+
}
22+
} else {
23+
if (hour > arr[2] || arr[2] === hour && tempMis > arr[3]) {
24+
res.push(`${start}-${end}`)
25+
return res
26+
}
27+
}
28+
let minute = zeroFill(tempMis)
29+
hour = zeroFill(hour)
30+
let resEnd = `${hour}:${minute}`
31+
res.push(`${start}-${resEnd}`)
32+
return resEnd === end ? res : _segment(resEnd, end, step)
33+
}
34+
_segment(start, end, step)
35+
return res
36+
}
37+
38+
// test case 1
39+
const result1 = timeSegment('08:30', '09:00', 45)
40+
console.log('result1', result1)
41+
// test case 2
42+
const result2 = timeSegment('06:30', '06:30', 45)
43+
console.log('result2', result2)
44+
// test case 3
45+
const result3 = timeSegment('06:30', '06:00', 45)
46+
console.log('result3', result3)
47+
```

0 commit comments

Comments
 (0)