过滤URL列表的简洁,面向功能的方法是什么,其中每个项目必须传递一系列测试?如果URL匹配任何测试,则应将其过滤掉。
我目前有:
var _ = require("underscore");
const anchors = [
{href:"https://example.org/contact"},
{href:"https://example.org/faq"},
{href:"https://example.org/contact"},
{href:"https://example.org/uploads/image-1024x1018.jpg"},
{href:"https://example.org/wp-json/oembed/1.0/embed?url=example"},
{href:"https://example.org/author/pm"},
{href:"https://example.org/wp/wp-login.php?action=lostpassword"},
{href:"https://example.org/wp/wp-login.php"},
{href:"https://example.org/feed"},
];
const tests = [
/\/wp\//,
/\/wp-json\//,
/\.jpg$/,
/\.png$/,
/\.gif$/,
]
function testAll(testString){
let pass = true;
_.each(tests, t => {
if(t.test(testString)) pass = false;
});
return pass;
}
console.log(anchors.map(anchor => {
return anchor.href;
}).filter(anchor => {
return testAll(anchor);
}));
但我怀疑testAll
可以更简洁的方式完成。
答案 0 :(得分:3)
我正在寻找的解决方案实际上是some
而不是every
,因为如果匹配任何的测试,我实际上需要拒绝该网址:
console.log(anchors.map(anchor => {
return anchor.href;
}).filter(anchor => {
// return testAll(anchor);
return !_.some(tests, t => {
return t.test(anchor);
})
}));
答案 1 :(得分:1)
您可以使用Array#every()
function testAll(testString){
return tests.every(reg => reg.test(testString));
}
答案 2 :(得分:1)
您可以使用Array#some
并将检查的否定结果用于过滤。
var anchors = [{ href:"https://example.org/contact" }, { href:"https://example.org/faq" }, { href:"https://example.org/contact" }, { href:"https://example.org/uploads/image-1024x1018.jpg" }, { href:"https://example.org/wp-json/oembed/1.0/embed?url=example" }, { href:"https://example.org/author/pm" }, { href:"https://example.org/wp/wp-login.php?action=lostpassword" }, { href:"https://example.org/wp/wp-login.php" }, { href:"https://example.org/feed" }],
tests = [/\/wp\//, /\/wp-json\//, /\.jpg$/, /\.png$/, /\.gif$/],
result = anchors.filter(({ href }) => !tests.some(t => t.test(href)));
console.log(result);