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

76 lines
2.3 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[]} -
*/
2023-11-11 16:13:36 +08:00
export function stringTokenizer<T>(
regExp: RegExp,
matchHandler: (text: string, match: boolean) => T,
textHandler?: (text: string, match: boolean) => T
): (str: string) => T[] {
2023-11-10 15:34:16 +08:00
2023-11-11 16:13:36 +08:00
const ifMatch = matchHandler;
const ifText = textHandler?textHandler: matchHandler;
2023-11-10 15:34:16 +08:00
2023-11-11 16:13:36 +08:00
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));
2023-11-10 15:34:16 +08:00
}
2023-11-11 16:13:36 +08:00
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;
};
}
/**
*
*
* undefinedtrue
* false
* @param source
* @param target
* @returns
*/
export function equalsIgnoreCase(
source: string | undefined,
target: string | undefined
) {
if (typeof source === "string" && typeof target === "string") {
return source.toLowerCase() === target.toLowerCase();
} else if (source === undefined && target === undefined) {
return true;
}
return false;
}
/**
*
*
* truefalse
* @param list
* @param search
* @returns
*/
export const includeIgnoreCase = (list: string[], search: string) => {
for (let i = 0; i < list.length; i++) {
let item = list[i];
if (equalsIgnoreCase(item, search)) {
return true;
}
}
return false;
};