text search algorithm in typescript

Text search is a common problem in programming. There are several algorithms to solve this problem, including binary search and linear search.

Linear search is a simple approach where you iterate over the characters in the text one by one and check for a match with the search string.

index.ts
function linearSearch(text: string, search: string) {
  for (let i = 0; i < text.length; i++) {
    let j = 0;
    while (j < search.length && text[i + j] === search[j]) {
      j++;
    }
    if (j === search.length) {
      return i;
    }
  }
  return -1;
}
261 chars
13 lines

Binary search is a more efficient algorithm that works by dividing the text in half and eliminating half of the remaining text on each comparison.

index.ts
function binarySearch(text: string, search: string) {
  let lo = 0;
  let hi = text.length - 1;
  while (lo <= hi) {
    let mid = Math.floor((lo + hi) / 2);
    let cmp = text.substr(mid, search.length).localeCompare(search);
    if (cmp === 0) {
      return mid;
    } else if (cmp < 0) {
      lo = mid + 1;
    } else {
      hi = mid - 1;
    }
  }
  return -1;
}
370 chars
17 lines

Both algorithms have their own strengths and weaknesses. Linear search is simple to implement, but not very efficient for large texts. Binary search is more efficient, but requires the text to be sorted and may not be suitable for dynamic environments.

Choose the algorithm that best fits your use case based on the size of the text, the number of queries, and the expected search patterns.

gistlibby LogSnag