Skip to content

Instantly share code, notes, and snippets.

@danielreiser
Last active August 3, 2021 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielreiser/6fb0e3a778ffe94ea1c8339d3076d8a6 to your computer and use it in GitHub Desktop.
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
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