From d491a46a215c8515547c9fdd28c2ad2ad50b0b69 Mon Sep 17 00:00:00 2001 From: 18alantom <2.alan.tom@gmail.com> Date: Fri, 26 Nov 2021 12:51:47 +0530 Subject: [PATCH] fix: autocomplete behaviour, use fuzzy matching --- src/components/Controls/AutoComplete.vue | 18 +++++---- src/components/Dropdown.vue | 48 ++++++++++++++++-------- src/utils.js | 30 +++++++++++++++ 3 files changed, 73 insertions(+), 23 deletions(-) diff --git a/src/components/Controls/AutoComplete.vue b/src/components/Controls/AutoComplete.vue index a5aba264..f7926223 100644 --- a/src/components/Controls/AutoComplete.vue +++ b/src/components/Controls/AutoComplete.vue @@ -34,6 +34,7 @@ diff --git a/src/utils.js b/src/utils.js index 01fbcf11..7cde188d 100644 --- a/src/utils.js +++ b/src/utils.js @@ -351,3 +351,33 @@ export function purgeCache(purgeAll = false) { delete frappe[d]; }); } + +export function fuzzyMatch(keyword, candidate) { + const keywordLetters = [...keyword]; + const candidateLetters = [...candidate]; + + let keywordLetter = keywordLetters.shift(); + let candidateLetter = candidateLetters.shift(); + + let isMatch = true; + let distance = 0; + + while (keywordLetter && candidateLetter) { + if (keywordLetter.toLowerCase() === candidateLetter.toLowerCase()) { + keywordLetter = keywordLetters.shift(); + } else { + distance += 1; + } + + candidateLetter = candidateLetters.shift(); + } + + if (keywordLetter !== undefined) { + distance = -1; + isMatch = false; + } else { + distance += candidateLetters.length; + } + + return { isMatch, distance }; +}