From 784eb8cd28a0fbbbc1a29fd8776654b0dab8a732 Mon Sep 17 00:00:00 2001 From: Mike Date: Sat, 22 Jul 2023 15:13:20 +0300 Subject: [PATCH] Optimazing iterate_grams function --- .../svelte/src/compiler/utils/fuzzymatch.js | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/packages/svelte/src/compiler/utils/fuzzymatch.js b/packages/svelte/src/compiler/utils/fuzzymatch.js index e7bb1ad697..f86990f872 100644 --- a/packages/svelte/src/compiler/utils/fuzzymatch.js +++ b/packages/svelte/src/compiler/utils/fuzzymatch.js @@ -19,18 +19,20 @@ const GRAM_SIZE_UPPER = 3; * @param {string} str2 */ function _distance(str1, str2) { - if (str1 === null && str2 === null) { + if (!str1 && !str2) { throw 'Trying to compare two null values'; } - if (str1 === null || str2 === null) return 0; + + if (!str1 || !str2) { + return 0 + } + str1 = String(str1); str2 = String(str2); + const distance = levenshtein(str1, str2); - if (str1.length > str2.length) { - return 1 - distance / str1.length; - } else { - return 1 - distance / str2.length; - } + + return 1 - distance / (str1.length > str2.length ? str1.length : str2.length); } // helper functions @@ -73,14 +75,15 @@ const non_word_regex = /[^\w, ]+/; function iterate_grams(value, gram_size = 2) { const simplified = '-' + value.toLowerCase().replace(non_word_regex, '') + '-'; const len_diff = gram_size - simplified.length; - const results = []; + const len_results = simplified.length - gram_size + 1 + const results = new Array(len_results); if (len_diff > 0) { for (let i = 0; i < len_diff; ++i) { value += '-'; } } - for (let i = 0; i < simplified.length - gram_size + 1; ++i) { - results.push(simplified.slice(i, i + gram_size)); + for (let i = 0; i < len_results; ++i) { + results[i] = simplified.slice(i, i + gram_size) } return results; }