Skip to content

Instantly share code, notes, and snippets.

@danielreiser
Last active August 7, 2021 14:14
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/8414fc81766d28c5031ee60aabe41aa3 to your computer and use it in GitHub Desktop.
Save danielreiser/8414fc81766d28c5031ee60aabe41aa3 to your computer and use it in GitHub Desktop.
Snippet of the levenshtein distance calculator top correct a misspelled route - Approach B
const { distance } = require('fastest-levenshtein')
// Approach B - Using distance which gives us more control in conjunction with a MAX_DISTANCE value
const routes = {
paymentMethods: 'paymentmethods',
accountData: 'account-data',
profile: 'profile',
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 MAX_DISTANCE = 2
const closestPathname = (inputPath) => {
const potentialRoutes = Object.entries(routes)
.map(([routeKey, route]) => ({ [routeKey]: distance(inputPath, route) }))
.sort((routeA, routeB) => {
const distanceA = Object.values(routeA)[0]
const distanceB = Object.values(routeB)[0]
if (distanceA < distanceB) {
return -1
} else if (distanceA > distanceB) {
return 1
}
return 0
})
.filter(route => Object.values(route)[0] <= MAX_DISTANCE)
.map(route => route ? routes[Object.keys(route)[0]] : null)
return potentialRoutes && potentialRoutes[0]
}
// Option A - Redirect the user instantly
window.location.href = closestPathname(path)
// Option B - Display a link on the page with the suggested route
document.querySelector('a.next-best-action').href = `${window.protocol}${window.host}/${closestPathname(path)}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment