forked from jordanthomas/jaro-winkler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (82 loc) · 2.14 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
(function (root) {
'use strict';
function extend(a, b) {
for (var property in b) {
if (b.hasOwnProperty(property)) {
a[property] = b[property];
}
}
return a;
}
function distance(s1, s2, options) {
var m = 0;
var defaults = { caseSensitive: true };
var settings = extend(defaults, options);
var i;
var j;
// Exit early if either are empty.
if (s1.length === 0 || s2.length === 0) {
return 0;
}
// Convert to upper if case-sensitive is false.
if (!settings.caseSensitive) {
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();
}
// Exit early if they're an exact match.
if (s1 === s2) {
return 1;
}
var range = (Math.floor(Math.max(s1.length, s2.length) / 2)) - 1;
var s1Matches = new Array(s1.length);
var s2Matches = new Array(s2.length);
for (i = 0; i < s1.length; i++) {
var low = (i >= range) ? i - range : 0;
var high = (i + range <= s2.length) ? (i + range) : (s2.length - 1);
for (j = low; j <= high; j++) {
if (s1Matches[i] !== true && s2Matches[j] !== true && s1[i] === s2[j]) {
++m;
s1Matches[i] = s2Matches[j] = true;
break;
}
}
}
// Exit early if no matches were found.
if (m === 0) {
return 0;
}
// Count the transpositions.
var k = 0;
var numTrans = 0;
for (i = 0; i < s1.length; i++) {
if (s1Matches[i] === true) {
for (j = k; j < s2.length; j++) {
if (s2Matches[j] === true) {
k = j + 1;
break;
}
}
if (s1[i] !== s2[j]) {
++numTrans;
}
}
}
var weight = (m / s1.length + m / s2.length + (m - (numTrans / 2)) / m) / 3;
var l = 0;
var p = 0.1;
if (weight > 0.7) {
while (s1[l] === s2[l] && l < 4) {
++l;
}
weight = weight + l * p * (1 - weight);
}
return weight;
}
if (typeof define === 'function' && define.amd) {
define([], distance);
} else if (typeof exports === 'object') {
module.exports = distance;
} else {
root.distance = distance;
}
})(this);