-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexMlArrayRescale.js
46 lines (38 loc) · 1.25 KB
/
indexMlArrayRescale.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
import { isAnyArray } from './indexIsAnyArray.js';
import max from './indexMlArraymax.js';
import min from './indexMlArraymin.js';
export default function rescale(input, options = {}) {
if (!isAnyArray(input)) {
throw new TypeError('input must be an array');
} else if (input.length === 0) {
throw new TypeError('input must not be empty');
}
let output;
if (options.output !== undefined) {
if (!isAnyArray(options.output)) {
throw new TypeError('output option must be an array if specified');
}
output = options.output;
} else {
output = new Array(input.length);
}
const currentMin = min(input);
const currentMax = max(input);
if (currentMin === currentMax) {
throw new RangeError(
'minimum and maximum input values are equal. Cannot rescale a constant array',
);
}
const {
min: minValue = options.autoMinMax ? currentMin : 0,
max: maxValue = options.autoMinMax ? currentMax : 1,
} = options;
if (minValue >= maxValue) {
throw new RangeError('min option must be smaller than max option');
}
const factor = (maxValue - minValue) / (currentMax - currentMin);
for (let i = 0; i < input.length; i++) {
output[i] = (input[i] - currentMin) * factor + minValue;
}
return output;
}