Last active
July 9, 2018 07:13
-
-
Save Jekiwijaya/a785de7433843c38fcd977f8f86e61a0 to your computer and use it in GitHub Desktop.
Path maching
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
import pathToRegexp from 'path-to-regexp'; | |
const compilePath = (pattern) => { | |
const keys = []; | |
const re = pathToRegexp(pattern, keys); | |
const compiledPattern = { re, keys }; | |
return compiledPattern; | |
}; | |
/** | |
input: | |
- path: '/path/7'; | |
- pattern: '/path/:id'; | |
output: | |
- { id : 7 } | |
*/ | |
function getParams(path, pattern) { | |
const { re, keys } = compilePath(pattern); | |
const match = re.exec(path); | |
if (!match) return {}; | |
const [url, ...values] = match; | |
const params = keys.reduce((memo, key, index) => { | |
memo[key.name] = values[index]; | |
return memo; | |
}, {}); | |
return params; | |
} | |
getParams('/path/7', '/path/:id'); // { id: 7 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment