lib/third_party/tracing/base/sorted_array_utils.js
function findClosestElementInSortedArray(ary, mapFn, val, maxDiff) {
    if (ary.length === 0)
      return null;

    var aftIdx = findLowIndexInSortedArray(ary, mapFn, val);
    var befIdx = aftIdx > 0 ? aftIdx - 1 : 0;

    if (aftIdx === ary.length)
      aftIdx -= 1;

    var befDiff = Math.abs(val - mapFn(ary[befIdx]));
    var aftDiff = Math.abs(val - mapFn(ary[aftIdx]));

    if (befDiff > maxDiff && aftDiff > maxDiff)
      return null;

    var idx = befDiff < aftDiff ? befIdx : aftIdx;
    return ary[idx];
  }
function findClosestElementInSortedArray(ary, mapFn, val, maxDiff) {
    if (ary.length === 0)
      return null;

    var aftIdx = findLowIndexInSortedArray(ary, mapFn, val);
    var befIdx = aftIdx > 0 ? aftIdx - 1 : 0;

    if (aftIdx === ary.length)
      aftIdx -= 1;

    var befDiff = Math.abs(val - mapFn(ary[befIdx]));
    var aftDiff = Math.abs(val - mapFn(ary[aftIdx]));

    if (befDiff > maxDiff && aftDiff > maxDiff)
      return null;

    var idx = befDiff < aftDiff ? befIdx : aftIdx;
    return ary[idx];
  }
function findClosestElementInSortedArray ( ary , mapFn , val , maxDiff ) { if ( ary . length === 0 ) return null ; var aftIdx = findLowIndexInSortedArray ( ary , mapFn , val ) ; var befIdx = aftIdx > 0 ? aftIdx - 1 : 0 ; if ( aftIdx === ary . length ) aftIdx -= 1 ; var befDiff = Math . abs ( val - mapFn ( ary [ befIdx ] ) ) ; var aftDiff = Math . abs ( val - mapFn ( ary [ aftIdx ] ) ) ; if ( befDiff > maxDiff && aftDiff > maxDiff ) return null ; var idx = befDiff < aftDiff ? befIdx : aftIdx ; return ary [ idx ] ; }
Finds the element in the array whose value is closest to |val|.

The same restrictions on sortedness as for findLowIndexInSortedArray apply.

@param {Array} ary An array of arbitrary objects.
@param {function():*} mapFn Callback that produces a key value
from an element in ary.
@param {number} val Value for which to search.
@param {number} maxDiff Maximum allowed difference in value between |val|
and an element's value.
@return {object} Object in the array whose value is closest to |val|, or
null if no object is within range.
Finds the element in the array whose value is closest to |val| .