forked from gajus/eslint-plugin-flowtype
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fuzzyStringMatch.js
48 lines (38 loc) · 1.1 KB
/
fuzzyStringMatch.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
import _ from 'lodash';
// Creates an array of letter pairs from a given array
// origin: https://github.com/d3/d3-array/blob/master/src/pairs.js
const arrayPairs = (array) => {
let ii = 0;
const length = array.length - 1;
let letter = array[0];
const pairs = new Array(length < 0 ? 0 : length);
while (ii < length) {
pairs[ii] = [letter, letter = array[++ii]];
}
return pairs;
};
/* eslint-enable */
export default (needle, haystack, weight = 0.5) => {
// Based on http://stackoverflow.com/a/23305385
const stringSimilarity = (str1, str2) => {
if (str1.length > 0 && str2.length > 0) {
const pairs1 = arrayPairs(str1);
const pairs2 = arrayPairs(str2);
const unionLen = pairs1.length + pairs2.length;
let hitCount;
hitCount = 0;
_.forIn(pairs1, (val1) => {
_.forIn(pairs2, (val2) => {
if (_.isEqual(val1, val2)) {
hitCount++;
}
});
});
if (hitCount > 0) {
return 2.0 * hitCount / unionLen;
}
}
return 0.0;
};
return stringSimilarity(needle, haystack) >= Number(weight);
};