ez-common-ts/src/commons/str-utils.ts

35 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-11-10 15:34:16 +08:00
/**
*
*
* @param {RegExp} regExp -
* @param {(text: string, match: boolean) => T} matchHandler -
* @param {(text: string, match: boolean) => T} [textHandler] -
* @return {(str: string) => T[]} -
*/
export function stringTokenizer<T>(
regExp: RegExp,
matchHandler: (text: string, match: boolean) => T,
textHandler?: (text: string, match: boolean) => T
): (str: string) => T[] {
const ifMatch = matchHandler;
const ifText = textHandler?textHandler: matchHandler;
return function (str: string) {
const result: T[] = [];
const matches = str.matchAll(regExp);
let index = 0;
for (const match of matches) {
const before = str.slice(index, match.index);
if (before) {
result.push(ifText(before, false));
}
result.push(ifMatch(match[0], true));
index = match.index! + match[0].length;
}
if (index < str.length) {
result.push(ifText(str.slice(index), false));
}
return result;
};
}