Last active
August 3, 2021 16:35
-
-
Save danielreiser/6fb0e3a778ffe94ea1c8339d3076d8a6 to your computer and use it in GitHub Desktop.
Snippet of the levenshtein distance calculator top correct a misspelled route - Approach A
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { closest, distance } = require('fastest-levenshtein') | |
// Approach A - Using closest | |
const routes = { | |
paymentMethods: 'paymentmethods', | |
accountData: 'account-data', | |
privacy: 'privacy', | |
privacySettings: 'privacy-settings', | |
} | |
// Get the current pathname and remove the leading slash (the pathname property always has a leading slash) | |
const path = window.location.pathname.substr(1) | |
// If the current path is not an exact match, we'll use the levenshtein distance calculation to get the closest match | |
if (!Object.values(routes).includes(path)) { | |
const closestPathnameA = closest(path, routes) | |
// Option A - Redirect the user instantly | |
window.location.href = closestPathname | |
// Option B - Display a link on the page with the suggested route | |
document.querySelector('a.next-best-action').href = `${window.protocol}${window.host}/${closestPathname}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment