UNPKG

ts-regexp

Version:

A RegExp wrapper providing stronger type safety.

73 lines (71 loc) 2.34 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { typedRegExp: () => typedRegExp }); module.exports = __toCommonJS(index_exports); var ternary = (condition) => (a, b) => condition ? a : b; var toPOJO = (instance) => Object.fromEntries( Object.getOwnPropertyNames( Object.getPrototypeOf(instance) ).map((name) => { const value = instance[name]; return [ name, typeof value === "function" ? value.bind(instance) : value ]; }) ); var strIncludes = (result, search) => result.includes(search); var typedRegExp = (pattern, flags) => { const regExp = new RegExp(pattern, flags); const resolvedFlags = flags ?? ""; const isGlobal = strIncludes(resolvedFlags, "g"); const replaceIn = (...args) => { const [source, ...rest] = args; return source.replace(regExp, ...rest); }; const replaceAllIn = (...args) => { const [source, ...rest] = args; return source.replaceAll(regExp, ...rest); }; const ternaryGlobalMethods = (condition) => ternary(condition)( { matchAllIn: (source) => source.matchAll(regExp), replaceAllIn }, {} ); const ret = { regExp, ...toPOJO(regExp), matchIn: (source) => source.match(regExp), replaceIn, searchIn: (source, ...args) => source.search(regExp, ...args), splitIn: (source, ...args) => source.split(regExp, ...args), ...ternaryGlobalMethods(isGlobal) }; return ret; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { typedRegExp });