Created
August 1, 2024 15:13
-
-
Save WomB0ComB0/09f7e66c88f5477ce94d2bdbdfc18869 to your computer and use it in GitHub Desktop.
Binary search text in Typescript
This file contains hidden or 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
const binarySearch = (source_text: string, target: string): [number, string] | null => { | |
const source_text_segments: string[] = (source_text.match(/[^.!?]+[.!?]+/g) || [source_text]).map(s => s.trim()); | |
const target_segment = target.trim(); | |
let result: [number, string] | null = null; | |
let left: number = 0; | |
let right: number = source_text_segments.length - 1; | |
while (left <= right) { | |
const mid = left + Math.floor((right - left) / 2); | |
const segment = source_text_segments[mid]; | |
if (segment === target_segment) { | |
result = [mid, segment]; | |
right = mid - 1; | |
} else if (segment < target_segment) { | |
left = mid + 1; | |
} else { | |
right = mid - 1; | |
} | |
} | |
if (result) { | |
let [firstIndex, firstSegment] = result; | |
while (firstIndex > 0 && source_text_segments[firstIndex - 1] === firstSegment) { | |
firstIndex--; | |
} | |
result = [firstIndex, firstSegment]; | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment