-
Notifications
You must be signed in to change notification settings - Fork 15
/
Config.ts
92 lines (74 loc) · 1.94 KB
/
Config.ts
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
import { assert, isArray, isInstanceOf, isNumber, isPlainObject } from '@/validation/assert';
export interface ConfigAttrs {
/** Minimum value JSR can accept */
min: number;
/** Maximum value JSR can accept */
max: number;
/**
* Step between values (can be float)
*
* @example
* for min: 0, and max: 100, and step: 1 it gives you 101 possible values
*
* @example
* for step: 0.1 it gives you 1001 possible values
*/
step: number;
/**
* Initial values for JSR. Determines number of supported values at all.
*/
initialValues: number[];
/**
* Container, that will contain all the modules.
*/
container: HTMLElement;
}
export interface ConfigDto extends ConfigAttrs {
stepDecimals: number;
valuesCount: number;
}
export class Config {
private attrs: ConfigAttrs;
private constructor (attrs: ConfigAttrs) {
this.attrs = attrs;
}
public toDto (): Readonly<ConfigDto> {
return Object.freeze({
...this.attrs,
stepDecimals: this.stepDecimals,
valuesCount: this.valuesCount,
});
}
public get max () {
return this.attrs.max;
}
public get min () {
return this.attrs.min;
}
public get step () {
return this.attrs.step;
}
/**
* Return how many decimal places the step has.
*/
public get stepDecimals (): number {
const compute = (n: number): number => {
if (n === 0) {
return 0;
}
return (n >= 1 ? 0 : (1 + compute(n * 10)));
};
return compute(this.step);
}
public get valuesCount (): number {
return this.attrs.initialValues.length;
}
public static createFromInput (attrs: ConfigAttrs): Config {
assert('min', attrs.min, isNumber);
assert('max', attrs.max, isNumber);
assert('step', attrs.step, isNumber);
assert('initialValues', attrs.initialValues, isArray(isNumber));
assert('container', attrs.container, isInstanceOf(window.HTMLElement));
return new Config(attrs);
}
}