UNPKG

vis-utils

Version:

Utility functions for data visualization

37 lines (31 loc) 1.28 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = findEqualSorted; var _binarySearch = require('binary-search'); var _binarySearch2 = _interopRequireDefault(_binarySearch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Helper function to find the item that matches this value. * Since it assumes the data is sorted, it does a binary search O(log 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 has this value or null if not found */ function findEqualSorted(array, value) { var accessor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (d) { return d; }; // binary search uses the value directly in comparisons, so make sure not to // run the accessor on it var index = (0, _binarySearch2.default)(array, value, function (a, b) { var aValue = a === value ? value : accessor(a); var bValue = b === value ? value : accessor(b); return aValue - bValue; }); return array[index]; }