Skip to content

Instantly share code, notes, and snippets.

@Jekiwijaya
Last active July 9, 2018 07:13
Show Gist options
  • Save Jekiwijaya/a785de7433843c38fcd977f8f86e61a0 to your computer and use it in GitHub Desktop.
Save Jekiwijaya/a785de7433843c38fcd977f8f86e61a0 to your computer and use it in GitHub Desktop.
Path maching
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