-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.mjs
More file actions
88 lines (79 loc) · 1.46 KB
/
helpers.mjs
File metadata and controls
88 lines (79 loc) · 1.46 KB
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
/**
*
* @param {number} ms
* @returns {Promise<void>}
*/
export function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
/**
* @param {(NodeJS.ErrnoException | string | null)[]} args
*/
export function handleError(...args) {
if (args[0]) {
console.log(...args)
}
}
export class RGB {
/** @type {number} */
r
/** @type {number} */
g
/** @type {number} */
b
/**
* @param {number} r
* @param {number} g
* @param {number} b
*/
constructor(r, g, b) {
this.update(r, g, b)
}
/**
* @param {unknown} v
* @returns {number}
*/
#validate(v) {
if (typeof v !== 'number' || Number.isNaN(v)) {
throw new Error(`Invalid RGB value: ${v}`)
}
return /** @type {number} */ (v)
}
/**
* @param {[number, number, number] | [RGB]} args
*/
update(...args) {
const [rgb] = args
const [r, g, b] = args
if (rgb instanceof RGB) {
this.r = rgb.r
this.g = rgb.g
this.b = rgb.b
} else {
this.r = this.#validate(r)
this.g = this.#validate(g)
this.b = this.#validate(b)
}
}
/**
* @returns {[number, number, number]}
*/
toArray() {
return [this.r, this.g, this.b]
}
toString() {
return `rgb(${this.r}, ${this.g}, ${this.b})`
}
serializeMQTT() {
return JSON.stringify({
R: this.r,
G: this.g,
B: this.b,
})
}
isOff() {
return this.r === 0 && this.g === 0 && this.b === 0
}
}