Skip to content

A fast, helpful, and open-source document parser

add case option

Logan Markewich987d1e8dfaf9
diff --git a/src/core/types.ts b/src/core/types.ts
index cbd3db7..e9ea6cc 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -310,8 +310,14 @@ export interface JsonTextItem {
* Options for {@link searchItems}.
*/
export interface SearchItemsOptions {
- /** Find text items containing this phrase (case-insensitive). Matches can span multiple adjacent items. */
+ /** Find text items containing this phrase. Matches can span multiple adjacent items. */
phrase: string;
+ /**
+ * Whether the search should be case-sensitive.
+ *
+ * @defaultValue `false`
+ */
+ caseSensitive?: boolean;
}
/**
diff --git a/src/processing/searchItems.test.ts b/src/processing/searchItems.test.ts
index dc9960a..9972714 100644
--- a/src/processing/searchItems.test.ts
+++ b/src/processing/searchItems.test.ts
@@ -40,13 +40,20 @@ describe("searchItems", () => {
expect(results[0].width).toBe(90);
});
- it("is case-insensitive", () => {
+ it("is case-insensitive by default", () => {
const items = [item("Revenue Grew", 10, 20, 100)];
const results = searchItems(items, { phrase: "revenue grew" });
expect(results).toHaveLength(1);
expect(results[0].text).toBe("revenue grew");
});
+ it("respects caseSensitive option", () => {
+ const items = [item("pH Level", 10, 20, 80)];
+ expect(searchItems(items, { phrase: "pH", caseSensitive: true })).toHaveLength(1);
+ expect(searchItems(items, { phrase: "ph", caseSensitive: true })).toHaveLength(0);
+ expect(searchItems(items, { phrase: "PH", caseSensitive: true })).toHaveLength(0);
+ });
+
it("returns empty array when no match", () => {
const items = [item("hello", 10, 20, 50)];
const results = searchItems(items, { phrase: "goodbye" });
diff --git a/src/processing/searchItems.ts b/src/processing/searchItems.ts
index fce3884..023f723 100644
--- a/src/processing/searchItems.ts
+++ b/src/processing/searchItems.ts
@@ -28,7 +28,9 @@ export function searchItems(
options: SearchItemsOptions
): JsonTextItem[] {
const results: JsonTextItem[] = [];
- const q = options.phrase.toLowerCase();
+ const caseSensitive = options.caseSensitive ?? false;
+ const normalize = caseSensitive ? (s: string) => s : (s: string) => s.toLowerCase();
+ const q = normalize(options.phrase);
let start = 0;
while (start < items.length) {
@@ -36,13 +38,13 @@ export function searchItems(
let found = false;
for (let end = start; end < items.length; end++) {
combined += (end > start ? " " : "") + items[end].text;
- if (combined.toLowerCase().includes(q)) {
+ if (normalize(combined).includes(q)) {
// Narrow from the left: drop leading items that aren't part of the match
let narrowed = combined;
let s = start;
while (s < end) {
const without = narrowed.slice(items[s].text.length + 1);
- if (without.toLowerCase().includes(q)) {
+ if (normalize(without).includes(q)) {
narrowed = without;
s++;
} else {