zarm
Version:
基于 React 的移动端UI库
29 lines (25 loc) • 1.03 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
export default function getClosestPoint(val, _ref) {
var _ref$marks = _ref.marks,
marks = _ref$marks === void 0 ? {} : _ref$marks,
_ref$step = _ref.step,
step = _ref$step === void 0 ? 1 : _ref$step,
_ref$min = _ref.min,
min = _ref$min === void 0 ? 0 : _ref$min,
_ref$max = _ref.max,
max = _ref$max === void 0 ? 10 : _ref$max;
if (max < min) {
throw new Error("\"max\" should be greater than \"min\". Got \"min\" = ".concat(min, ", \"max\" = ").concat(max));
}
var points = Object.keys(marks || {}).map(parseFloat);
if (step !== null) {
var maxSteps = Math.floor((max - min) / step);
var steps = Math.min((val - min) / step, maxSteps);
var closestStep = Math.round(steps) * step + min;
points.push(closestStep);
}
var diffs = points.map(function (point) {
return Math.abs(val - point);
});
return points[diffs.indexOf(Math.min.apply(Math, _toConsumableArray(diffs)))];
}