@modern-kit/utils
Version:
1 lines • 3.01 kB
Source Map (JSON)
{"version":3,"file":"index.mjs","sources":["../../../src/string/countSubstringOccurrences/internal.ts","../../../src/string/countSubstringOccurrences/index.ts"],"sourcesContent":["const escapeRegExp = (str: string): RegExp => {\n const escaped = str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(escaped, 'g');\n};\n\nexport const countAllowOverlap = (source: string, target: string) => {\n const regex = escapeRegExp(target);\n let count = 0;\n let match = regex.exec(source);\n\n while (match !== null) {\n count++;\n regex.lastIndex = match.index + 1;\n\n match = regex.exec(source);\n }\n\n return count;\n};\n\nexport const countExceptOverlap = (source: string, target: string) => {\n const regex = escapeRegExp(target);\n\n const matches = source.match(regex);\n return matches ? matches.length : 0;\n};\n","import { countAllowOverlap, countExceptOverlap } from './internal';\n\ninterface CountSubstringOccurrencesOptions {\n overlap: boolean;\n}\n\n/**\n * @description 문자열에서 특정 하위 문자열이 얼마나 반복 등장했는지 횟수를 반환하는 함수입니다.\n *\n * @param {string} source - 검색할 대상이 되는 문자열\n * @param {string} target - 찾고자 하는 부분 문자열\n * @param {CountSubstringOccurrencesOptions} options - 설정 옵션\n * @param {boolean} options.overlap - 중첩 계산 여부\n * @returns {number} 부분 문자열이 발견된 횟수\n *\n * @example\n * countSubstringOccurrences(\"hello hello\", \"hello\") // 결과: 2\n *\n * @example\n * countSubstringOccurrences(\"aaaa\", \"aa\", { overlap: true }) // 결과: 3\n * countSubstringOccurrences(\"aaaa\", \"aa\", { overlap: false }) // 결과: 2\n */\nexport function countSubstringOccurrences(\n source: string,\n target: string,\n options: CountSubstringOccurrencesOptions = { overlap: false }\n): number {\n if (target === '') return 0;\n\n return options.overlap\n ? countAllowOverlap(source, target)\n : countExceptOverlap(source, target);\n}\n"],"names":[],"mappings":"AAAA,MAAM,YAAA,GAAe,CAAC,GAAA,KAAwB;AAC5C,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,OAAA,CAAQ,qBAAA,EAAuB,MAAM,CAAA;AACzD,EAAA,OAAO,IAAI,MAAA,CAAO,OAAA,EAAS,GAAG,CAAA;AAChC,CAAA;AAEO,MAAM,iBAAA,GAAoB,CAAC,MAAA,EAAgB,MAAA,KAAmB;AACnE,EAAA,MAAM,KAAA,GAAQ,aAAa,MAAM,CAAA;AACjC,EAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,EAAA,IAAI,KAAA,GAAQ,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA;AAE7B,EAAA,OAAO,UAAU,IAAA,EAAM;AACrB,IAAA,KAAA,EAAA;AACA,IAAA,KAAA,CAAM,SAAA,GAAY,MAAM,KAAA,GAAQ,CAAA;AAEhC,IAAA,KAAA,GAAQ,KAAA,CAAM,KAAK,MAAM,CAAA;AAAA,EAC3B;AAEA,EAAA,OAAO,KAAA;AACT,CAAA;AAEO,MAAM,kBAAA,GAAqB,CAAC,MAAA,EAAgB,MAAA,KAAmB;AACpE,EAAA,MAAM,KAAA,GAAQ,aAAa,MAAM,CAAA;AAEjC,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA;AAClC,EAAA,OAAO,OAAA,GAAU,QAAQ,MAAA,GAAS,CAAA;AACpC,CAAA;;ACHO,SAAS,0BACd,MAAA,EACA,MAAA,EACA,UAA4C,EAAE,OAAA,EAAS,OAAM,EACrD;AACR,EAAA,IAAI,MAAA,KAAW,IAAI,OAAO,CAAA;AAE1B,EAAA,OAAO,OAAA,CAAQ,UACX,iBAAA,CAAkB,MAAA,EAAQ,MAAM,CAAA,GAChC,kBAAA,CAAmB,QAAQ,MAAM,CAAA;AACvC;;;;"}