Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/natural/distance/jaro-winkler_distance.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ function distance (s1, s2) {
return 0
}

const matchWindow = (Math.floor(Math.max(s1.length, s2.length) / 2.0)) - 1
// The window is negative for strings of length 1, so clamp it to 0
const matchWindow = Math.max(0, (Math.floor(Math.max(s1.length, s2.length) / 2.0)) - 1)
const matches1 = new Array(s1.length)
const matches2 = new Array(s2.length)
let m = 0 // number of matches
Expand Down Expand Up @@ -115,7 +116,7 @@ function JaroWinklerDistance (s1, s2, options = {}) {
const jaro = (options.dj === undefined) ? distance(s1, s2) : options.dj
const p = 0.1 // default scaling factor
let l = 0 // length of the matching prefix
while (s1[l] === s2[l] && l < 4) {
while (l < 4 && l < s1.length && l < s2.length && s1[l] === s2[l]) {
l++
}

Expand Down
14 changes: 14 additions & 0 deletions spec/jaro-winkler_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ describe('jaro-winkler', function () {
expect(approxEql(JaroWinklerDistance('MARTHA', 'MARHTA', { ignoreCase: true }), 0.96111)).toBeTruthy()
expect(JaroWinklerDistance('abcd', 'ABCD', { ignoreCase: true })).toBe(1)
})

it('should handle strings of length 1', function () {
expect(JaroWinklerDistance('a', 'a', {})).toBe(1)
expect(JaroWinklerDistance('a', 'b', {})).toBe(0)
expect(JaroWinklerDistance('A', 'a', {})).toBe(0)
expect(JaroWinklerDistance('A', 'a', { ignoreCase: true })).toBe(1)
expect(JaroWinklerDistance('a', 'A', { ignoreCase: true })).toBe(1)
expect(JaroWinklerDistance('A', 'b', { ignoreCase: true })).toBe(0)
})

it('should not count a matching prefix longer than the strings', function () {
// Both strings are 2 characters long, so the matching prefix is at most 2: 0.5 + 2 * 0.1 * (1 - 0.5)
expect(approxEql(JaroWinklerDistance('Ab', 'aB', { ignoreCase: true, dj: 0.5 }), 0.6)).toBeTruthy()
})
it('should not fail while passing no options', function () {
expect(approxEql(JaroWinklerDistance('check', 'chakk'), 0.78666)).toBeTruthy()
})
Expand Down