Skip to content

Instantly share code, notes, and snippets.

@Palisand
Created January 27, 2018 18:43
Show Gist options
  • Save Palisand/c2dd916e0c90b8f5c540d1c8990abd60 to your computer and use it in GitHub Desktop.
Save Palisand/c2dd916e0c90b8f5c540d1c8990abd60 to your computer and use it in GitHub Desktop.
Map with Regex Keys
function getFromRegexKeys(key, map) {
for (let [re, val] of map.entries()) {
if (re.test(key)) {
return val(key.match(re));
}
}
}
const map = new Map([
[/^foo\/(.+)$/, matchResults => matchResults[1]],
[/^bar\/(.+)\/(.+)\/(.+)$/, matchResults => matchResults[2]],
]);
getFromRegexKeys('foo/', map); // === undefined
getFromRegexKeys('foo/quuz', map); // === 'quuz'
getFromRegexKeys('bar/baz/qux/quz', map); // === 'qux'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment