UNPKG

@discoveryjs/discovery

Version:

Frontend framework for rapid data (JSON) analysis, shareable serverless reports and dashboards

55 lines (54 loc) 2.08 kB
import { isRegExp } from "./is-type.js"; const stopSymbol = Symbol("stop-match"); function matchWithRx(str, pattern, lastIndex = 0) { const offset = lastIndex !== 0 ? str.slice(lastIndex).search(pattern) : str.search(pattern); return offset !== -1 ? { offset: lastIndex + offset, length: RegExp.lastMatch.length } : null; } ; function matchWithString(str, pattern, lastIndex) { const offset = str.indexOf(pattern, lastIndex); return offset !== -1 ? { offset, length: pattern.length } : null; } ; export function match(text, pattern, ignoreCase = false) { if (isRegExp(pattern)) { return ignoreCase && !pattern.ignoreCase ? new RegExp(pattern, pattern.flags + "i").test(text) : pattern.test(text); } if (typeof pattern === "string") { return ignoreCase ? String(text).toLowerCase().includes(pattern.toLowerCase()) : String(text).includes(pattern); } return false; } export function matchAll(text, pattern, onText, onMatch, ignoreCase = false) { if (!isRegExp(pattern) && typeof pattern !== "string") { onText(text, true); return; } let matchText = String(text); if (ignoreCase) { if (typeof pattern === "string") { matchText = matchText.toLowerCase(); pattern = pattern.toLowerCase(); } else { if (!pattern.ignoreCase) { pattern = new RegExp(pattern, pattern.flags + "i"); } } } let lastIndex = 0; let stopMatch = false; do { const match2 = stopMatch ? null : typeof pattern === "string" ? matchWithString(matchText, pattern, lastIndex) : matchWithRx(matchText, pattern, lastIndex); if (match2 === null || match2.length === 0 && match2.offset === lastIndex) { onText(lastIndex > 0 ? text.slice(lastIndex) : text, true); break; } if (match2.length !== 0) { if (match2.offset !== lastIndex) { onText(text.slice(lastIndex, match2.offset), false); } stopMatch = onMatch(text.substr(match2.offset, match2.length), stopSymbol) === stopSymbol; } lastIndex = match2.offset + match2.length; } while (lastIndex !== text.length); }