-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplify lookup, add reverse support
- Loading branch information
Showing
3 changed files
with
54 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,49 @@ | ||
'use strict'; | ||
|
||
/** | ||
* @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ | ||
* Binary search | ||
* @param {array} table - the table search. must be sorted! | ||
* @param {string} key - property name for the value in each entry | ||
* @param {number} value - value to find | ||
* @private | ||
*/ | ||
export function _lookup(table, key, value) { | ||
let lo = 0; | ||
let hi = table.length - 1; | ||
let mid, i0, i1; | ||
let lo = 0; | ||
let mid; | ||
|
||
while (lo >= 0 && lo <= hi) { | ||
while (hi - lo > 1) { | ||
mid = (lo + hi) >> 1; | ||
i0 = mid > 0 && table[mid - 1] || null; | ||
i1 = table[mid]; | ||
if (table[mid][key] < value) { | ||
lo = mid; | ||
} else { | ||
hi = mid; | ||
} | ||
} | ||
|
||
if (!i0) { | ||
// given value is outside table (before first item) | ||
return {lo: null, hi: i1, loIndex: null, hiIndex: mid}; | ||
} else if (i1[key] < value) { | ||
lo = mid + 1; | ||
} else if (i0[key] > value) { | ||
hi = mid - 1; | ||
return {lo, hi}; | ||
} | ||
|
||
/** | ||
* Reverse binary search | ||
* @param {array} table - the table search. must be sorted! | ||
* @param {string} key - property name for the value in each entry | ||
* @param {number} value - value to find | ||
* @private | ||
*/ | ||
export function _rlookup(table, key, value) { | ||
let hi = table.length - 1; | ||
let lo = 0; | ||
let mid; | ||
|
||
while (hi - lo > 1) { | ||
mid = (lo + hi) >> 1; | ||
if (table[mid][key] < value) { | ||
hi = mid; | ||
} else { | ||
return {lo: i0, hi: i1, loIndex: mid - 1, hiIndex: mid}; | ||
lo = mid; | ||
} | ||
} | ||
|
||
// given value is outside table (after last item) | ||
return {lo: i1, hi: null, loIndex: mid, hiIndex: null}; | ||
return {lo, hi}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters