Skip to content

Commit

Permalink
feat: _leven to support limit argument
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillgroshkov committed Apr 3, 2024
1 parent b6dc77f commit 662ec5d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/string/leven.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,13 @@ test('leven', () => {
expect(_leven('cat', 'cat')).toBe(0)
expect(_leven('cat', 'bat')).toBe(1)
expect(_leven('cat', 'octocat')).toBe(4)

// with limit
expect(_leven('cat', 'octocat', 0)).toBe(0)
expect(_leven('cat', 'octocat', 1)).toBe(1)
expect(_leven('cat', 'octocat', 2)).toBe(2)
expect(_leven('cat', 'octocat', 3)).toBe(3)
expect(_leven('cat', 'octocat', 4)).toBe(4)
expect(_leven('cat', 'octocat', 5)).toBe(4)
expect(_leven('cat', 'octocat', 15)).toBe(4)
})
9 changes: 7 additions & 2 deletions src/string/leven.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ const characterCodeCache: number[] = []
* Modified version of: https://github.com/sindresorhus/leven/
*
* Returns a Levenshtein distance between first and second word.
*
* `limit` optional parameter can be used to limit the distance calculation
* and skip unnecessary iterations when limit is reached.
*/
export function _leven(first: string, second: string): number {
if (first === second) {
export function _leven(first: string, second: string, limit?: number): number {
if (first === second || limit === 0) {
return 0
}

Expand Down Expand Up @@ -47,6 +50,7 @@ export function _leven(first: string, second: string): number {
secondLength -= start

if (firstLength === 0) {
if (limit && secondLength >= limit) return limit
return secondLength
}

Expand All @@ -66,6 +70,7 @@ export function _leven(first: string, second: string): number {
bCharacterCode = second.charCodeAt(start + index2)
temporary = index2++
result = index2
if (limit && result >= limit) return limit // exit early on limit

for (index = 0; index < firstLength; index++) {
temporary2 = bCharacterCode === characterCodeCache[index] ? temporary : temporary + 1
Expand Down

0 comments on commit 662ec5d

Please sign in to comment.