Trigrams and closest match

Getting trigrams and searching the closest match

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/550221/1664485/Trigrams%20and%20closest%20match.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

//GETTING TRIGRAMS:
function getTrigrams(value) {
  const trigrams = [];
  // Pad the string to handle edge cases for shorter strings and beginning/end trigrams
  const paddedValue = ' ' + value + ' '; 

  for (let i = 0; i < paddedValue.length - 2; i++) {
    trigrams.push(paddedValue.substring(i, i + 3));
  }
  return trigrams;
  }//Closing getTrigrams()-Function

  
function trigramSimilarity(stringA, stringB) {
  if (stringA === stringB) {
    return 1; // Strings are identical
  }

  const trigramsA = new Set(getTrigrams(stringA.toLowerCase())); // Convert to lowercase for case-insensitive comparison
  const trigramsB = new Set(getTrigrams(stringB.toLowerCase()));

  let commonTrigramsCount = 0;
  for (const trigram of trigramsA) {
    if (trigramsB.has(trigram)) {
      commonTrigramsCount++;
    }
  }

  const totalUniqueTrigrams = trigramsA.size + trigramsB.size - commonTrigramsCount;

  if (totalUniqueTrigrams === 0) {
    return 0; // Avoid division by zero if both strings are empty or result in no trigrams
  }

  return commonTrigramsCount / totalUniqueTrigrams;
  }//Closing-trigramSimilarity()-Function
  
  
  
  //SEARCHING CLOSEST MATCH:
  function findClosestMatchTrigrams(targetString, stringArray) {
        let closestMatch = null;
        let highestSimilarity = -1;

        for (const str of stringArray) {
            const similarity = trigramSimilarity(targetString, str);
            if (similarity > highestSimilarity) {
                highestSimilarity = similarity;
                closestMatch = str;
            }
        }

        return {
            closestMatch: closestMatch,
            similarityFraction: highestSimilarity
        };
    }//Closing-findClosestMatchTrigrams()-Function