File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1212 *
1313 * @param {number } value - The value to search for in the array.
1414 * @param {array } array - The array to search, which must be sorted.
15+ * @param {string } [key] - An optional property key. If specified the array elements property will be checked against value.
1516 *
16- * @return {number } The nearest value found in the array.
17+ * @return {number|object } The nearest value found in the array, or if a `key` was given, the nearest object with the matching property value .
1718 */
18- var FindClosestInSorted = function ( value , array )
19+ var FindClosestInSorted = function ( value , array , key )
1920{
2021 if ( ! array . length )
2122 {
2223 return NaN ;
2324 }
24- else if ( array . length === 1 || value < array [ 0 ] )
25+ else if ( array . length === 1 )
2526 {
2627 return array [ 0 ] ;
2728 }
2829
2930 var i = 1 ;
31+ var low ;
32+ var high ;
3033
31- while ( array [ i ] < value )
34+ if ( key )
3235 {
33- i ++ ;
36+ if ( value < array [ 0 ] [ key ] )
37+ {
38+ return array [ 0 ] ;
39+ }
40+
41+ while ( array [ i ] [ key ] < value )
42+ {
43+ i ++ ;
44+ }
45+ }
46+ else
47+ {
48+ while ( array [ i ] < value )
49+ {
50+ i ++ ;
51+ }
3452 }
3553
36- var low = array [ i - 1 ] ;
37- var high = ( i < array . length ) ? array [ i ] : Number . POSITIVE_INFINITY ;
54+ if ( i > array . length )
55+ {
56+ i = array . length ;
57+ }
3858
39- return ( ( high - value ) <= ( value - low ) ) ? high : low ;
59+ if ( key )
60+ {
61+ low = array [ i - 1 ] [ key ] ;
62+ high = array [ i ] [ key ] ;
63+
64+ return ( ( high - value ) <= ( value - low ) ) ? array [ i ] : array [ i - 1 ] ;
65+ }
66+ else
67+ {
68+ low = array [ i - 1 ] ;
69+ high = array [ i ] ;
70+
71+ return ( ( high - value ) <= ( value - low ) ) ? high : low ;
72+ }
4073} ;
4174
4275module . exports = FindClosestInSorted ;
You can’t perform that action at this time.
0 commit comments