Boolean Concatenation? What's the real term for this pattern?
Please consider the following function body:
var isValidated = true;
$(selector1).each(function(){
//do validation with local f()...
isValidated = f() && isValidated;
});
$(selector2).each(function(){
//do validation with local f()...
isValidated = f() && isValidated;
});
$(selector3).each(function(){
//do validation with local f()...
isValidated = f() && isValidated;
});
return isValidated;
My description of the progress of isValidated
is Boolean concatenation---but there has to be an official, computer-science term for this thing. What is it? To clarify, the idea here is to let each $()
block run---but when any one of these blocks have a validation failure the results of this failure must return false
over all blocks (true && true && false == false
). So, like many programmers, I am using some kind of a pattern but we often don't know what it is called. So does this pattern resemble anything useful开发者_Go百科?
Boolean Logic. (and look at the "chaining operations" section).
Not sure if this is a named pattern per se, but I just wanted to point out a minor observation... Since you are just returning boolean, it would be better to switch your checks so that after the first failure the logic will simply short circuit as false without running additional functions unnecessarily:
isValidated = isValidated && f();
The only reason to ensure you still run every f() is if they are doing something like marking UI fields with errors for the user. If they are simply validating, no need to run them once the outer check is false.
I'm assuming from your use of .each() that you also have access to an .inject() function, which is what I'd recommend using when you're building a single value from an enumerable.
function validated(a) {
return a.inject(true, function(acc, el){ return(acc && f()); });
}
return validated($(selector1)) && validated($(selector2)) && validated($(selector3));
精彩评论