-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(utils): 특수 문자에 대한 개수와 공백에 대한 처리 추가 (#168)
* fix(utils): 특수 문자에 대한 개수와 공백에 대한 처리 추가 * chore: console.log 제거 * refactor(utils): 함수 배치 수정 및 while 문 가독성 향상 * docs(utils): 중복 문자열에 대한 옵션 허용 문서화
- Loading branch information
Showing
3 changed files
with
56 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 36 additions & 3 deletions
39
packages/utils/src/string/countSubstringOccurrences/index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,39 @@ | ||
export const countSubstringOccurrences = (source: string, target: string) => { | ||
const regex = new RegExp(target, 'g'); | ||
const matches = source.match(regex); | ||
type Options = { overlap: boolean }; | ||
|
||
const escapeRegExp = (str: string): string => { | ||
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | ||
}; | ||
|
||
const countAllowOverlap = (source: string, regex: RegExp) => { | ||
let count = 0; | ||
let match = regex.exec(source); | ||
|
||
while (match !== null) { | ||
count++; | ||
regex.lastIndex = match.index + 1; | ||
|
||
match = regex.exec(source); | ||
} | ||
|
||
return count; | ||
}; | ||
|
||
const countExceptOverlap = (source: string, regex: RegExp) => { | ||
const matches = source.match(regex); | ||
return matches ? matches.length : 0; | ||
}; | ||
|
||
export const countSubstringOccurrences = ( | ||
source: string, | ||
target: string, | ||
options: Options = { overlap: false } | ||
): number => { | ||
if (target === '') return 0; | ||
|
||
const escapedTarget = escapeRegExp(target); | ||
const regex = new RegExp(escapedTarget, 'g'); | ||
|
||
return options.overlap | ||
? countAllowOverlap(source, regex) | ||
: countExceptOverlap(source, regex); | ||
}; |