From 301cbbcd07015a436d190885171d4c34ba181d44 Mon Sep 17 00:00:00 2001 From: Fuwn Date: Sun, 11 Feb 2024 00:03:45 -0800 Subject: fix(error): levenshtein closest --- src/lib/Error/path.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'src/lib/Error') diff --git a/src/lib/Error/path.ts b/src/lib/Error/path.ts index 40f50b7c..ea11fa69 100644 --- a/src/lib/Error/path.ts +++ b/src/lib/Error/path.ts @@ -1,11 +1,13 @@ +import levenshtein from 'fast-levenshtein'; + export const closest = (path: string, suggestions: string[]) => { - const partialMatch = suggestions.find((suggestion) => suggestion.includes(path)); + const suggestionsWithDistance = suggestions.map((suggestion) => { + const distance = levenshtein.get(path, suggestion); - if (partialMatch) return partialMatch; + return { suggestion, distance }; + }); - const closestMatch = suggestions.reduce((prev, curr) => { - return prev.length > curr.length ? prev : curr; - }, ''); + suggestionsWithDistance.sort((a, b) => a.distance - b.distance); - return closestMatch; + return suggestionsWithDistance[0].suggestion; }; -- cgit v1.2.3