Skip to content

Instantly share code, notes, and snippets.

@chenglou
Created November 9, 2022 10:44
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 chenglou/4fdfc725ca6f116338241c71a3b9f5bd to your computer and use it in GitHub Desktop.
Save chenglou/4fdfc725ca6f116338241c71a3b9f5bd to your computer and use it in GitHub Desktop.
let routes = {
// Regular JS regex over cleaned up URL.
'book/(\\d+)?/edit': (id) => console.log('handleBookEdit', id),
'book/(\\d+)?/.+': (_id, _) => console.log('noSuchBookOperation'),
'book/(\\d+)?': (id) => console.log('getBook', id),
'shop/(\\d+)?/(\\d+)?': (a, b) => console.log('showSecretShopPage', a, b),
'shop/index': () => console.log('showShoppingPage'),
'shop/(.+)': (rest) => console.log('nestedMatch', rest),
'shop': () => console.log('showShoppingPage'),
'.+': (_) => console.log('showNotFoundPage'),
'': () => console.log('showMainPage'),
}
matchRoute(routes, 'book/12/edit') // edit book
matchRoute(routes, 'book/10/oops') // invalid operation
matchRoute(routes, 'shop/13/54') // show secret
matchRoute(routes, 'shop/bla/blabla/10') // nested match
matchRoute(routes, 'bla') // 404
matchRoute(routes, '') // main page
function matchRoute(cases, url) {
for (let regexString in cases) {
let match = url.match(new RegExp(regexString))
if (match != null) {
cases[regexString](...match.slice(1))
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment