You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.4 KiB
51 lines
1.4 KiB
import { isAnyArray } from 'is-any-array';
|
|
import max from 'ml-array-max';
|
|
import min from 'ml-array-min';
|
|
|
|
function rescale(input) {
|
|
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
|
|
if (!isAnyArray(input)) {
|
|
throw new TypeError('input must be an array');
|
|
} else if (input.length === 0) {
|
|
throw new TypeError('input must not be empty');
|
|
}
|
|
|
|
var 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);
|
|
}
|
|
|
|
var currentMin = min(input);
|
|
var currentMax = max(input);
|
|
|
|
if (currentMin === currentMax) {
|
|
throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');
|
|
}
|
|
|
|
var _options$min = options.min,
|
|
minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,
|
|
_options$max = options.max,
|
|
maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;
|
|
|
|
if (minValue >= maxValue) {
|
|
throw new RangeError('min option must be smaller than max option');
|
|
}
|
|
|
|
var factor = (maxValue - minValue) / (currentMax - currentMin);
|
|
|
|
for (var i = 0; i < input.length; i++) {
|
|
output[i] = (input[i] - currentMin) * factor + minValue;
|
|
}
|
|
|
|
return output;
|
|
}
|
|
|
|
export { rescale as default };
|
|
|