-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathutil.js
93 lines (78 loc) · 2.05 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function formatTime(time) {
if (typeof time !== 'number' || time < 0) {
return time
}
const hour = parseInt(time / 3600, 10)
time %= 3600
const minute = parseInt(time / 60, 10)
time = parseInt(time % 60, 10)
const second = time
return ([hour, minute, second]).map(function (n) {
n = n.toString()
return n[1] ? n : `0${n}`
}).join(':')
}
function formatLocation(longitude, latitude) {
if (typeof longitude === 'string' && typeof latitude === 'string') {
longitude = parseFloat(longitude)
latitude = parseFloat(latitude)
}
longitude = longitude.toFixed(2)
latitude = latitude.toFixed(2)
return {
longitude: longitude.toString().split('.'),
latitude: latitude.toString().split('.')
}
}
function fib(n) {
if (n < 1) return 0
if (n <= 2) return 1
return fib(n - 1) + fib(n - 2)
}
function formatLeadingZeroNumber(n, digitNum = 2) {
n = n.toString()
const needNum = Math.max(digitNum - n.length, 0)
return new Array(needNum).fill(0).join('') + n
}
function formatDateTime(date, withMs = false) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
const ms = date.getMilliseconds()
let ret = `${[year, month, day].map(value => formatLeadingZeroNumber(value, 2)).join('-')} ${[hour, minute, second].map(value => formatLeadingZeroNumber(value, 2)).join(':')}`
if (withMs) {
ret += `.${formatLeadingZeroNumber(ms, 3)}`
}
return ret
}
function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i], 10)
const num2 = parseInt(v2[i], 10)
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
module.exports = {
formatTime,
formatLocation,
fib,
formatDateTime,
compareVersion
}