One of strings in array to match an expression

后端 未结 5 1671
花落未央
花落未央 2021-02-12 22:29

The Problem:

I have an array of promises which is resolved to an array of strings. Now the test should pass if at least one of the strings matc

5条回答
  •  耶瑟儿~
    2021-02-12 22:53

    As said in the comments, although I initially use map, reduce would allow you to do what you need, and in this caste at least makes a lot more sense:

    protractor.promise.all([text1, text2, text3]).then(function (values) {
        expect(
            values.reduce(function(p, v) {
                return v.match(/expression/) || p;
            }, false)
        ).toBe(true);
    });
    

    Or writing the same thing, but using ES6 arrow functions:

    protractor.promise.all([text1, text2, text3]).then(function(values) {
        exptect(
            values.reduce( (p, v) => v.match(/expression/) || p, false )
        ).toBe(true);
    });
    

    Both do the same thing, the reduce callback will default to false, until the v.match expression evaluates to true.
    I'm assuming this is obvious to most people, but I thought I'd provide both syntaxes and some explanation for future reference


    Perhaps this solution could be optimized a bit more, to stop matching the pattern once a single match has been found:

    protractor.promise.all([text1, text2, text3]).then(function (values) {
        expect(
            values.reduce(function(p, v) {
                return p || !!v.match(/expression/);
            }, false)
        ).toBe(true);
    });
    

    All I did was to use the current reduce value as default (once that has been set to true, there's no point in testing any other string value). To ensure v.match evaluates to a boolean instead of an array, I just used !!v.match(). That part is optional though. In ES6, the same thing looks like this:

    protractor.promise.all([text1, text2, text3]).then(function(values) {
        exptect(
            values.reduce( (p, v) => p || !!v.match(/expression/), false )
        ).toBe(true);
    });
    

    This might perform better with big data sets (considering the match calls stop once the first match was found, as opposed to v.match being called every time).

提交回复
热议问题