Naive String Matcher

Posted by Dustin Boston in .

Source Code Listing

code.ts

// NAIVE STRING MATCHER(T, P)
// n = T.length
// m = P.length
// for s = 0 to n - m
//   if P[1..m] == T[s + 1..s + m]
//     print “Pattern occurs with shift” s

export function naiveStringMatcher(text: string, pattern: string) {
  const n = text.length;
  const m = pattern.length;

  let count = 0;

  for (let s = 0; s <= n - m; s++) {
    const a = pattern.slice(0, m);
    const b = text.slice(s, s + m);
    if (a === b) {
      count++;
    }
  }

  return count;
}

test.ts

import {expect, test} from "bun:test";
import {naiveStringMatcher} from "./code.ts";

test(`find pattern "aab" in "acaabc"`, () => {
  const actual = naiveStringMatcher("acaabc", "aab");
  const expected = 1;
  expect(actual).toEqual(expected);
});