Last active
November 30, 2016 00:23
-
-
Save berdosi/cc9b0a6bd6d0babeffa162b91449eb90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* code based on pseudocode from https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm#Calculating_distance */ | |
interface replacePair { | |
first: string; | |
second: string; | |
cost: number | |
} | |
class replacePairCollection { | |
replacePairs: Array<replacePair>; | |
constructor(_replacePairs: Array<replacePair>) { | |
this.replacePairs = _replacePairs; | |
} | |
inCollection(first: string, second: string): boolean { | |
for (let replacePair of this.replacePairs) | |
if ((first === replacePair.first) && (second === replacePair.second)) | |
return true; | |
return false; | |
} | |
getCost(first: string, second: string): number { | |
for (let replacePair of this.replacePairs) | |
if ((first === replacePair.first) && (second === replacePair.second)) | |
return replacePair.cost; | |
} | |
} | |
interface costObject { | |
replacePairs: replacePairCollection; | |
defaultReplaceCost: number; | |
deleteCost: number; | |
insertCost: number | |
} | |
export default function LevenshteinOCR(fromString: string, toString: string, override: costObject) { | |
const fromLength: number = fromString.length; | |
const toLength: number = toString.length; | |
var distanceArray: Array<number>; | |
for (let i = 1; i <= fromLength; i++) distanceArray[i, 0] = i; | |
for (let j = 1; j <= toLength; j++) distanceArray[j, 0] = j; | |
for (let j = 1; j <= toLength; j++) | |
for (let i = 1; i <= fromLength; i++) | |
distanceArray[i, j] = | |
Math.min( | |
distanceArray[i - 1, j - 1] + fromString[i - 1] === fromString[j - 1] | |
? 0 | |
: (override.replacePairs.inCollection(fromString[i - 1], fromString[j - 1]) | |
? override.replacePairs.getCost(fromString[i - 1], fromString[j - 1]) | |
: override.defaultReplaceCost), | |
distanceArray[i - 1, j] + override.deleteCost, | |
distanceArray[i, j - 1] + override.insertCost); | |
return distanceArray[toLength, fromLength]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment