* Finds the node matching the given selection criteria. * * When searching for higher nodes, returns the lowest node that is higher than * the value. When searching for lower nodes, returns the highest node that is * lower than the value. * * By default, only accepts a node exactly
(
value: T,
select?: "higher" | "lower",
returnIfFound: boolean = true,
)
| 241 | * @returns The node that matched, or null if none matched |
| 242 | */ |
| 243 | #findNode( |
| 244 | value: T, |
| 245 | select?: "higher" | "lower", |
| 246 | returnIfFound: boolean = true, |
| 247 | ): BinarySearchNode<T> | null { |
| 248 | const compare = getCompare(this); |
| 249 | |
| 250 | let node: BinarySearchNode<T> | null = getRoot(this); |
| 251 | let result: BinarySearchNode<T> | null = null; |
| 252 | while (node) { |
| 253 | const order = compare(value, node.value); |
| 254 | if (order === 0 && returnIfFound) return node; |
| 255 | |
| 256 | let direction: Direction = order < 0 ? "left" : "right"; |
| 257 | if (select === "higher" && order === 0) { |
| 258 | direction = "right"; |
| 259 | } else if (select === "lower" && order === 0) { |
| 260 | direction = "left"; |
| 261 | } |
| 262 | |
| 263 | if ( |
| 264 | (select === "higher" && direction === "left") || |
| 265 | (select === "lower" && direction === "right") |
| 266 | ) { |
| 267 | result = node; |
| 268 | } |
| 269 | |
| 270 | node = node[direction]; |
| 271 | } |
| 272 | return result; |
| 273 | } |
| 274 | |
| 275 | /** |
| 276 | * Finds the lowest (leftmost) value in the binary search tree which is |