@smakss/search
Version:
Enhance your searching capabilities with @smakss/search. Effortlessly find keywords in arrays, nested arrays, and objects, perfect for deep search needs in various data structures.
51 lines (50 loc) • 2.43 kB
TypeScript
import type { SearchItem, KeyOf } from './types';
/**
* Searches for matches within an object based on a regex pattern.
* If a match is found within the specified keys, it adds the object to the results.
*
* @template T - The type of the object to search within, extending SearchItem.
* @param {T} object - The object to search within.
* @param {string[]} keys - The keys to include or exclude in the search.
* @param {boolean} include - Whether to include or exclude the specified keys in the search.
* @param {RegExp} regex - The regex pattern to match against the object values.
* @param {T[]} results - The array to store matching objects.
*
* @example
* // Define an object to search
* const person = { name: "John", lastName: "Doe" };
* const results = [];
*
* // Search within the object for the name 'John'
* searchWithinObject(person, ['name'], true, /John/i, results);
*
* // results will contain the person object
* console.log(results); // [{ name: "John", lastName: "Doe" }]
*/
export declare function searchWithinObject<T extends SearchItem>(object: T, keys: KeyOf<T>[], include: boolean, regex: RegExp, results: T[]): void;
/**
* Recursively searches through items for matches based on a regex pattern.
* It handles both arrays and individual objects.
*
* @template T - The type of the items to search through, extending SearchItem.
* @param {T | T[]} items - The items to search through. Can be a single item or an array of items.
* @param {string[]} keys - The keys to include or exclude in the search.
* @param {boolean} include - Whether to include or exclude the specified keys in the search.
* @param {RegExp} regex - The regex pattern to match against item values.
* @param {SearchItem[]} results - The array to store matching items.
*
* @example
* // Define a list of objects to search
* const people = [
* { name: "John", lastName: "Doe" },
* { name: "Jane", lastName: "Doe" },
* ];
* const searchResults = [];
*
* // Recursively search for the term 'doe' in the list of people
* recursiveSearch(people, ['lastName'], true, /doe/i, searchResults);
*
* // searchResults will contain both person objects
* console.log(searchResults); // [{ name: "John", lastName: "Doe" }, { name: "Jane", lastName: "Doe" }]
*/
export declare function recursiveSearch<T extends SearchItem>(items: T | T[], keys: KeyOf<T>[], include: boolean, regex: RegExp, results: T[]): void;