按测试列表筛选

3

如何简洁地对URL列表进行过滤,使得每一个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


Array.prototype.every - Mulan
你可以始终执行 tests.every(t => t.test(stringHere));every 只有在数组中的每个元素都返回 true 时才会返回 true,因此你的函数就变成了:let anchorsPass = anchors.every(a => tests.every(t => t.test(a.href)); - tymeJV
/$.png/ 是在做什么? $ 是字符串结尾的标志。 - Nina Scholz
@NinaScholz 错误已经修复,通过编辑完成。 - T3db0t
3个回答

3
我需要的解决方案实际上是 some 而不是 every,因为如果 URL 匹配了任何一个测试,我实际上需要拒绝它:
console.log(anchors.map(anchor => {
    return anchor.href;
}).filter(anchor => {
    // return testAll(anchor);
    return !_.some(tests, t => {
        return t.test(anchor);
    })
}));

1
你可能也可以省略整个 map 调用 - 只需 .filter(anchor => { // return testAll(anchor); return !_.some(tests, t => { return t.test(anchor.href); }) }) - tymeJV
你也可以使用内置于 Arraysome 函数,而不是使用 underscore.js (tests.some(t => t.test(anchor.href)))。 - user184994
map-然后-filter会导致对同一集合进行多次迭代 - 如果要避免这种情况,可以使用anchors.filter(({href}) => tests.every(t => !t.test(href)))或使用Array.prototype.reduce - Mulan

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);


1
你可以使用 Array#every()
function testAll(testString){
    return tests.every(reg => reg.test(testString));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接