是否有一种更有效的方法来再现下面的代码,这涉及从一个包含正则表达式对象和函数组成的键组成的映射中检索捕获组匹配,这些函数接受一个键与正则表达式匹配的结果?
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'发布于 2018-01-27 22:20:32
不要运行test和match,这两次应用正则表达式。就这么做
function getFromRegexKeys(key, map) {
for (const [re, val] of map.entries()) {
const res = re.exec(key); // or `key.match(re)`
if (res) return val(res);
}
}https://stackoverflow.com/questions/48479349
复制相似问题