predictype
Version:
PredicType is a library of pre-built and tested predicates for TypeScript, covering various data types and operations.
41 lines (40 loc) • 1.63 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringSubstring = stringSubstring;
const strings_js_1 = require("../../enums/strings.js");
/**
* Checks if a string contains, excludes, starts with, or ends with a substring using the specified operation.
*
* @param source The string to check.
* @param oper The substring operation to perform (e.g. 'includes', 'starts_with').
* @param target The substring to check for.
* @returns True if the substring check is valid according to the operator, otherwise false.
*
* @throws {Error} If the operation is not recognized.
*
* @example
* const str = 'foobar';
*
* stringSubstring(str, 'includes', sub); // true
* stringSubstring(str, 'starts_with', sub); // true
*
* @remarks
* Supported Operators:
* - **INCLUDES**: String includes the substring
* - **EXCLUDES**: String does not include the substring
* - **STARTS_WITH**: String starts with the substring
* - **ENDS_WITH**: String ends with the substring
*/
function stringSubstring(source, oper, target) {
const operators = {
[strings_js_1.StringSubstringEnum.INCLUDES]: (a, b) => a.includes(b),
[strings_js_1.StringSubstringEnum.EXCLUDES]: (a, b) => !a.includes(b),
[strings_js_1.StringSubstringEnum.STARTS_WITH]: (a, b) => a.startsWith(b),
[strings_js_1.StringSubstringEnum.ENDS_WITH]: (a, b) => a.endsWith(b),
};
const enumOper = typeof oper === 'string' ? oper : oper;
const fn = operators[enumOper];
if (!fn)
throw new Error(`Unknown StringSubstring operation: ${oper}`);
return fn(source, target);
}
;