From 557563f331630666c276805ab4955c998af3fedd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maximilian=20Kr=C3=B6g?= Date: Sun, 12 Jul 2020 17:11:59 +0200 Subject: [PATCH] Update scoring / indexing code Add dict / word as parameters to updateScore function so it does not need to be created in each loop, and shorten it a bit. --- examples/index.js | 39 ++++++++++++----------------- examples/webpack/example-builder.js | 15 +++-------- 2 files changed, 20 insertions(+), 34 deletions(-) diff --git a/examples/index.js b/examples/index.js index 7c50304a5c..cc73582dff 100644 --- a/examples/index.js +++ b/examples/index.js @@ -29,40 +29,33 @@ if (text.length === 0) { return info.examples; } - const words = text.split(/\W+/); + const words = text.toLowerCase().split(/\W+/); const scores = {}; - for (let i = 0; i < words.length; ++i) { - const word = words[i].toLowerCase(); - let dict = info.index[word]; - const updateScores = function () { - // eslint-disable-next-line prefer-const - for (let exIndex in dict) { - const count = dict[exIndex]; - if (scores[exIndex]) { - if (scores[exIndex][word]) { - scores[exIndex][word] += count; - } else { - scores[exIndex][word] = count; - } - } else { - scores[exIndex] = {}; - scores[exIndex][word] = count; - } + const updateScores = function (dict, word) { + // eslint-disable-next-line prefer-const + for (let exIndex in dict) { + let exScore = scores[exIndex]; + if (!exScore) { + exScore = {}; + scores[exIndex] = exScore; } - }; + exScore[word] = (exScore[word] || 0) + dict[exIndex]; + } + }; + words.forEach(function (word) { + const dict = info.index[word]; if (dict) { - updateScores(); + updateScores(dict, word); } else { const r = new RegExp(word); // eslint-disable-next-line prefer-const for (let idx in info.index) { if (r.test(idx)) { - dict = info.index[idx]; - updateScores(); + updateScores(info.index[idx], word); } } } - } + }); const examples = []; // eslint-disable-next-line prefer-const for (let exIndex in scores) { diff --git a/examples/webpack/example-builder.js b/examples/webpack/example-builder.js index 6851012834..39a94acec7 100644 --- a/examples/webpack/example-builder.js +++ b/examples/webpack/example-builder.js @@ -42,26 +42,19 @@ function createWordIndex(exampleData) { const keys = ['shortdesc', 'title', 'tags']; exampleData.forEach((data, i) => { keys.forEach((key) => { - let text = data[key]; + let text = data[key] || ''; if (Array.isArray(text)) { text = text.join(' '); } - const words = text ? text.split(/\W+/) : []; + const words = text.toLowerCase().split(/\W+/); words.forEach((word) => { if (word) { - word = word.toLowerCase(); let counts = index[word]; - if (counts) { - if (index in counts) { - counts[i] += 1; - } else { - counts[i] = 1; - } - } else { + if (!counts) { counts = {}; - counts[i] = 1; index[word] = counts; } + counts[i] = (counts[i] || 0) + 1; } }); });