简体   繁体   中英

how to validate a value with a set of rules given in an array?

i have a value say 3000, and i have a set of rule in an array

var rule = [greaterthan-2000,lessthan-4000,greaterthan-5000,lessthan-6000];

Now how will i validate the value (3000) with the set of rules given in the array.

(Note: which condition satisfy first, that will be the result. In this case, '3000' satisfy rule[0] and rule[1], but the output should be rule[0])

you can prob use some Some iterates and array and runs a given function for each member of the array. Once it you return true it stops scanning. So you could use that to test each of the rule function (assuming they take an int) and once found save the found result and return. Here is an example:

var x;
var foundRule = null;
rules.some(function (rule) {
  if (rule.call(x)) {
    foundRule = rule    
    return true;
  }
}

You could get the operator from this function.

var getop = function(input)
{
    if(input.includes("greaterthan"))
        return '>'
    else if(input.includes("lessthan"))
        return '<'
}

and the number from this function.

var getnum = function(input)
{
    var pos = input.indexOf("-");
    return(input.substring(pos+1,input.length))
}

Now check for the conditions using the check function.

var check = function(number, conditions)
    {
    for(var i in conditions)
    {
        var op = getop(conditions[i]);
        var cond_no = getnum(conditions[i]);

            if(op == '>')
                if(number > cond_no)
                    return i
            if(op == '<')
                if(number < cond_no)
                    return i

    }
    }

Now declare your conditions and the number for it and get the output

var conditions =  ["greaterthan-2000","lessthan-4000","greaterthan-5000","lessthan-6000"];
var number = 3000;
console.log("rule["+check(number,conditions)+"]");

this would result in rule[0]

This is a work around using function itself:

 var rules = [ function(x) { return x > 2000; }, function(x) { return x < 4000; }, function(x) { return x > 5000; }, function(x) { return x < 6000; } ]; var indexOfRule = function(x) { var j = -1; for (var i = 0, l = rules.length; l > i; i++) { if (rules[i](x)) { //function call, matches rule j = i; break; } } return j; }; alert(indexOfRule(3000)); //0 alert(indexOfRule(0)); //1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM