@davidwells/matcher matches items against strings, regular expressions, functions, arrays, and object criteria.
Full documentation, synced from the source README:
A flexible utility for matching and finding items based on various criteria. This utility provides functions to match items against strings, regular expressions, functions, arrays, or objects.
npm install @davidwells/matcherThe matcher utility provides three main functions:
matchItem: Check if an item matches specific criteriafindMatchingItems: Find all items that match the criteriafindFirstMatch: Find the first item that matches the criteriaconst { matchItem, findMatchingItems, findFirstMatch } = require('@davidwells/matcher')
// Sample items
const items = [
{ text: 'Apple', match: 'fruit.apple' },
{ text: 'Banana', match: 'fruit.banana' },
{ text: 'Carrot', match: 'vegetable.carrot' }
]
// Match by string
matchItem(items[0], 'fruit.apple') // true
matchItem(items[0], 'Apple') // true
// Match by regex
matchItem(items[0], /fruit/) // true
// Match by function
matchItem(items[0], item => item.text.startsWith('A')) // true
// Find all fruits
const fruits = findMatchingItems(items, /fruit/)
// [{ text: 'Apple', match: 'fruit.apple' }, { text: 'Banana', match: 'fruit.banana' }]
// Find first vegetable
const vegetable = findFirstMatch(items, /vegetable/)
// { text: 'Carrot', match: 'vegetable.carrot' }matchItem(itemOrItems, matcher)Determines if an item matches the specified matcher criteria.
itemOrItems (Item|Array<Item>): The item or array of items to checkmatcher (ValidMatcher|Array<ValidMatcher>): The criteria to match againstboolean: True if the item matches the criteria, false otherwisefindMatchingItems(items, matcher)Find all items that match the specified criteria.
items (Array<Item>): Array of items to searchmatcher (ValidMatcher): The criteria to match againstArray<Item>: Array of matching itemsfindFirstMatch(items, matcher)Find the first item that matches the specified criteria.
items (Array<Item>): Array of items to searchmatcher (ValidMatcher): The criteria to match againstItem|undefined: First matching item or undefined if none foundThe matcher utility supports the following types of matchers:
text or match propertytext or match propertymatch property containing a valid matcherItems should follow this structure:
interface Item {
text: string; // The display text of the item
match: string; // The matching identifier of the item
index?: number; // Optional index position of the item
}