Javascript 按测试列表筛选
过滤URL列表的简洁、面向功能的方法是什么,其中每个项目都必须通过一系列测试?如果URL与任何测试匹配,则应将其过滤掉 我目前有:Javascript 按测试列表筛选,javascript,node.js,regex,functional-programming,Javascript,Node.js,Regex,Functional Programming,过滤URL列表的简洁、面向功能的方法是什么,其中每个项目都必须通过一系列测试?如果URL与任何测试匹配,则应将其过滤掉 我目前有: var _ = require("underscore"); const anchors = [ {href:"https://example.org/contact"}, {href:"https://example.org/faq"}, {href:"https://example.org/contact"}, {href:"h
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
可以用更简洁的方式来完成。您可以使用
我寻找的解决方案实际上是
some
,而不是every
,因为如果URL与以下任何测试匹配,我实际上需要拒绝它:
console.log(anchors.map(anchor => {
return anchor.href;
}).filter(anchor => {
// return testAll(anchor);
return !_.some(tests, t => {
return t.test(anchor);
})
}));
您可以使用并获取检查的否定结果进行筛选
var锚=[{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" }],
测试=[/\/wp\/,/\/wp json\/,/\.jpg$/,/\.png$/,/\.gif$/],
result=anchors.filter({href})=>!tests.some(t=>t.test(href));
console.log(result);
Array.prototype.each
你总是可以做测试。each(t=>t.test(stringHere));
每一个都返回true
只有当数组中的每个元素都返回true
,那么你的函数就变成了:让锚点通过=锚点。each(a=>tests.each(t=>t=>t.test(a.href))/$.png/
在做什么?$
是字符串符号的结尾。@NinaScholz错误已用edit修复。您可能也可以省略整个映射
调用-只是.filter(anchor=>{//return testAll(anchor);return!u.some(tests,t=>{return t.test(anchor.href)})
您也可以使用数组中内置的some
函数,而不是使用underline.js(tests.some(t=>t.test(anchor.href))
)映射
-然后-过滤器
会在同一个集合中引起多次迭代-您可以使用锚。过滤器({href}=>测试(t=>!t.test(href))
或者使用Array.prototype.reduce
来避免这种情况
console.log(anchors.map(anchor => {
return anchor.href;
}).filter(anchor => {
// return testAll(anchor);
return !_.some(tests, t => {
return t.test(anchor);
})
}));