-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutilities.js
71 lines (59 loc) · 1.87 KB
/
utilities.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
import normalize_url from 'normalize-url'
import url from 'node:url'
class Utilities {
isValidURL(string) {
try {
new URL(string)
return true
}
catch (err) {
return false
}
}
tryValidURL(theUrl, hostname) {
// Relative URL
if (theUrl.indexOf('//') === -1 && theUrl.indexOf('/') === 0) {
theUrl = new URL(theUrl, hostname).href
}
// Missing protocol URL. Must be placed after relative URL convert
if (url.parse(theUrl).protocol === null) {
theUrl = `https://${theUrl}`
}
if (this.isValidURL(theUrl)) {
return this.normalizeURL(theUrl)
}
return false
}
normalizeURL(url) {
return normalize_url(url, {
stripHash: true,
sortQueryParameters: true,
removeTrailingSlash: false,
})
}
toTimestamp(strDate) {
let datum = Date.parse(strDate)
return datum / 1000
}
// https://stackoverflow.com/a/34270811/8329480
toHumans(seconds) {
const levels = [
[Math.floor(seconds / 31536000), 'years'],
[Math.floor((seconds % 31536000) / 86400), 'days'],
[Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
[Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
[(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
]
let returnText = ''
let i = 0, max = levels.length
for (; i < max; i++) {
if (levels[i][0] === 0) {
continue
}
returnText += ' ' + levels[i][0] + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length - 1) : levels[i][1]);
}
return returnText.trim()
}
}
const utils = new Utilities()
export default utils