smartfuzzy/ts/smartfuzzy.classes.smartfuzzy.ts

62 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-08-19 13:17:59 +00:00
import * as plugins from './smartfuzzy.plugins';
export let standardExport = 'Hi there! :) This is an exported string';
export type TDictionaryMap = { [key: string]: number };
2018-08-19 13:17:59 +00:00
export class Smartfuzzy {
dictionary: string[];
constructor(dictionary: string[]) {
this.dictionary = dictionary;
}
/**
* adds words to the dictionary
* @param payloadArg
*/
addToDictionary(payloadArg: string | string[]) {
if (Array.isArray(payloadArg)) {
this.dictionary = this.dictionary.concat(payloadArg);
} else {
this.dictionary.push(payloadArg);
}
}
/**
* returns the closest match for a given string
* @param stringArg
*/
2021-10-03 15:12:02 +00:00
getChangeScoreForString(stringArg: string): TDictionaryMap {
const dictionaryMap: TDictionaryMap = {};
2018-08-19 13:17:59 +00:00
for (const wordArg of this.dictionary) {
dictionaryMap[wordArg] = plugins.leven(stringArg, wordArg);
}
return dictionaryMap;
2018-08-19 13:17:59 +00:00
}
getClosestMatchForString(stringArg: string): string {
2018-08-19 13:17:59 +00:00
const fuseDictionary: { name: string }[] = [];
for (const wordArg of this.dictionary) {
fuseDictionary.push({
name: wordArg
});
}
const fuseOptions = {
2018-08-19 13:17:59 +00:00
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: ['name']
};
const fuse = new plugins.fuseJs(fuseDictionary, fuseOptions);
const fuzzyResult = fuse.search(stringArg);
let closestMatch: string = null;
if(fuzzyResult.length > 0) {
2021-10-03 15:12:02 +00:00
closestMatch = fuzzyResult[0].item.name
}
return closestMatch;
2018-08-19 13:17:59 +00:00
}
}