match-detector
Version:
Match strings to "detect subjects"
63 lines (62 loc) • 2.37 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MatchDetector = void 0;
const tslib_1 = require("tslib");
const easy_json_database_1 = tslib_1.__importDefault(require("easy-json-database"));
const string_similarity_1 = require("string-similarity");
class MatchDetector {
constructor(databasePath) {
this.database = new easy_json_database_1.default(databasePath);
}
addElement({ power, word }) {
if (this.database.has(word))
return false;
this.database.set(word, power);
return true;
}
removeElement(word) {
if (!this.database.has(word))
return false;
this.database.delete(word);
return true;
}
get elements() {
return this.database.all().map(x => ({ word: x.key, power: x.data }));
}
test(text) {
const includes = this.database.all().filter(x => text.includes(x.key)).map(x => ({ key: x.key, data: parseInt(x.data) }));
const percent = includes.length * 100 / text.split(/ +/g).length;
if (percent >= this.getPercentageByStringLength(text.length))
return true;
const highestPower = includes.sort((a, b) => a.data - b.data)[0].data;
if (includes.filter(x => x.data === highestPower).length * 100 / includes.length >= 60 && highestPower > 5)
return true;
if (includes.map(x => x.data).sort((a, b) => a + b)[0] >= 4 * includes.length)
return true;
let matches = 0;
for (const item of text.split(/ +/g)) {
if ((0, string_similarity_1.findBestMatch)(item, includes.map(x => x.key)).bestMatch.rating > 0.6)
matches++;
}
const matchesPercent = matches * 100 / text.split(/ +/g).length;
if (matchesPercent >= this.getPercentageByStringLength(text.length))
return true;
return false;
}
getPercentageByStringLength(length) {
if (length < 10)
return 100;
if (length < 25)
return 50;
if (length < 40)
return 60;
if (length < 50)
return 50;
if (length < 60)
return 40;
if (length < 200)
return 20;
return 10;
}
}
exports.MatchDetector = MatchDetector;