UNPKG

vis-utils

Version:

Utility functions for data visualization

34 lines (30 loc) 994 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = findClosestUnsorted; /** * Helper function to compute distance and find the closest item * Since it assumes the data is unsorted, it does a linear scan O(n). * * @param {Array} array the input array to search * @param {Number} value the value to match against (typically pixels) * @param {Function} accessor applied to each item in the array to get equivalent * value to compare against * @return {Any} The item in the array that is closest to `value` */ function findClosestUnsorted(array, value) { var accessor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (d) { return d; }; var closest = null; var closestDist = null; array.forEach(function (elem) { var dist = Math.abs(accessor(elem) - value); if (closestDist == null || dist < closestDist) { closestDist = dist; closest = elem; } }); return closest; }