-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutil.js
124 lines (98 loc) · 1.92 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const Color = require('color')
function toInt (val) {
switch (typeof val) {
case 'object' :
case 'function' :
case 'undefined' :
case 'symbol' :
return 0
}
if (typeof val === 'boolean') {
return val ? 1 : 0
}
val = parseInt(val, 10)
if (isNaN(val)) {
return 0
}
return val
}
function color (val) {
let _isFormatted = false
let _isValidated = false
let _isNormalized = false
let _formatted = null
let _isValid = false
let _normalized = null
function format () {
if (_isFormatted) {
return _formatted
}
_isFormatted = true
_formatted = null
if (typeof val !== 'string') {
return _formatted
}
const rgba = val.trim().split(',').filter(v => v !== '')
if (val.indexOf(',') > -1) {
if (rgba.length === 3 || rgba.length === 4) {
_formatted = rgba
.map(v => parseFloat(v.trim(), 10))
.filter(v => !isNaN(v))
} else {
_formatted = null
}
} else if (val.length === 3 || val.length === 6) {
_formatted = '#' + val
}
return _formatted
}
function validate () {
if (_isValidated) {
return _isValid
}
_isValidated = true
if (!_isFormatted) {
_formatted = format(val)
}
try {
Color(_formatted)
_isValid = true
} catch (err) {
_isValid = false
}
return _isValid
}
function normalize () {
if (_isNormalized) {
return _normalized
}
_isNormalized = true
if (!_isValidated) {
_isValid = validate(val)
}
if (_isValid) {
_normalized = Color(_formatted).object()
} else {
_normalized = null
}
return _normalized
}
return {
format,
validate,
normalize
}
}
function findKey (obj, func) {
for (const key in obj) {
if (func(obj[key])) {
return key
}
}
return undefined
}
module.exports = {
toInt,
color,
findKey
}