codsworth-namegen/js/jaro-winkler.js

133 lines
3.1 KiB
JavaScript

/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Jordan Thomas
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
"use strict";
var jaro_winkler = function(a, b, options)
{
// Load default options
options = optionDefault(
{
"caseSensitive" : true
},
options
);
// Convert to lowercase if not case-sensitive
if(!options.caseSensitive)
{
a = a.toLowerCase();
b = b.toLowerCase();
}
var alen = a.length,
blen = b.length;
// Short-circuit if either is empty
if(alen === 0 || blen === 0)
{
return 0;
}
// Short-circuit if exact match
if(a === b)
{
return 1;
}
// Calculate difference
var i, j;
var low, high,
m = 0,
range = (Math.floor(Math.max(alen, blen) / 2)) - 1,
aMatches = [],
bMatches = [];
// Find matches
for(i = 0; i < alen; i++)
{
low = ((i >= range) ? i - range : 0);
high = ((i + range <= blen) ? (i + range) : (blen - 1));
for(j = low; j <= high; j++)
{
if(aMatches[i] !== true && bMatches[j] !== true && a[i] === b[j])
{
aMatches[i] = true;
bMatches[j] = true;
m++;
break;
}
}
}
// Short-circuit if not matches found
if(m === 0)
{
return 0;
}
// Count transpositions
var k = 0,
numTrans = 0;
for(i = 0; i < alen; i++)
{
if(aMatches[i] === true)
{
for(j = k; j < blen; j++)
{
if(bMatches[j] === true)
{
k = j + 1;
break;
}
}
if(a[i] !== b[j])
{
numTrans++;
}
}
}
var weight = (((m / alen) + (m / blen) + (m - (numTrans / 2)) / m) / 3);
var l = 0,
p = 0.1;
if(weight > 0.7)
{
while(a[l] === b[l] && l < 4)
{
l++;
}
weight += l * p * (1 - weight);
}
return weight;
};