Created
January 27, 2018 18:43
-
-
Save Palisand/c2dd916e0c90b8f5c540d1c8990abd60 to your computer and use it in GitHub Desktop.
Map with Regex Keys
This file contains hidden or 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
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