Skip to content

Commit 9f85c0f

Browse files
committed
new optional argument key which will allow you to scan a top-level property of any object in the given sorted array and get the closest match to it.
1 parent fa23202 commit 9f85c0f

1 file changed

Lines changed: 41 additions & 8 deletions

File tree

src/utils/array/FindClosestInSorted.js

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,64 @@
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

4275
module.exports = FindClosestInSorted;

0 commit comments

Comments
 (0)