"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function stripBOM(content) {
    content = content.toString();
    // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
    // because the buffer-to-string conversion in `fs.readFileSync()`
    // translates it to FEFF, the UTF-16 BOM.
    if (content.charCodeAt(0) === 0xfeff) {
        content = content.slice(1);
    }
    return content;
}
exports.stripBOM = stripBOM;
function parseBOM(content) {
    return JSON.parse(stripBOM(content));
}
exports.parseBOM = parseBOM;
function compareTwoStrings(str1, str2) {
    if (!str1.length && !str2.length)
        return 1;
    if (!str1.length || !str2.length)
        return 0;
    if (str1.toUpperCase() === str2.toUpperCase())
        return 1;
    if (str1.length === 1 && str2.length === 1)
        return 0;
    var pairs1 = wordLetterPairs(str1);
    var pairs2 = wordLetterPairs(str2);
    var union = pairs1.length + pairs2.length;
    var intersection = 0;
    pairs1.forEach(function (pair1) {
        for (var i = 0, pair2 = void 0; (pair2 = pairs2[i]); i++) {
            if (pair1 !== pair2)
                continue;
            intersection++;
            pairs2.splice(i, 1);
            break;
        }
    });
    return (intersection * 2) / union;
}
function findBestMatch(mainString, targetStrings) {
    if (!areArgsValid(mainString, targetStrings))
        throw new Error('Bad arguments: First argument should be a string, second should be an array of strings');
    var ratings = targetStrings.map(function (target) { return ({
        target: target,
        rating: compareTwoStrings(mainString, target.value),
    }); });
    var bestMatch = Array.from(ratings).sort(function (a, b) { return b.rating - a.rating; })[0];
    return { ratings: ratings, bestMatch: bestMatch };
}
exports.findBestMatch = findBestMatch;
function flattenDeep(arr) {
    return Array.isArray(arr)
        ? arr.reduce(function (a, b) { return a.concat(flattenDeep(b)); }, [])
        : [arr];
}
function areArgsValid(mainString, targetStrings) {
    if (typeof mainString !== 'string')
        return false;
    if (!Array.isArray(targetStrings))
        return false;
    if (!targetStrings.length)
        return false;
    if (targetStrings.find(function (s) { return typeof s.value !== 'string'; }))
        return false;
    return true;
}
function letterPairs(str) {
    var pairs = [];
    for (var i = 0, max = str.length - 1; i < max; i++)
        pairs[i] = str.substring(i, i + 2);
    return pairs;
}
function wordLetterPairs(str) {
    var pairs = str
        .toUpperCase()
        .split(' ')
        .map(letterPairs);
    return flattenDeep(pairs);
}
//# sourceMappingURL=string.js.map