Comment detail

法演算 (Nested Flatten)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
normalize_law = function( law ){
    return function(num){
        num %= law;
        num += num < 0 ? law : 0;
        return num;
    }
}

opfunc = (function(){
    var func = {
        '+' : function(x,y){return x+y },
        '-' : function(x,y){return x-y },
        '*' : function(x,y){return x*y }
    };
    return function(opcode){ return func[opcode]; };
})();

calc = function( exp, law ){
    if( ! exp.match(/(-?\d+)\s*([-*+])\s*(-?\d+)/) ){
        return null;
    }
    var ope1 = RegExp.$1;
    var opcode = RegExp.$2;
    var ope2 = RegExp.$3;
    var normalize = normalize_law( law );
    var opcode = opfunc(opcode);
    return opcode 
            ? normalize( opcode( normalize(ope1), normalize(ope2) ))
            : null;
}

alert( calc("1+2",10) );
alert( calc("7 + 3",10) );
alert( calc("11 + 12",10) );
alert( calc("3 - 2",10) );
alert( calc("2 - 3",10) );
alert( calc("2 * 3",10) );
alert( calc("11 * 12",10) );
alert( calc("18 * 39",10) );
alert( calc("6 / 2",10) );

Index

Feed

Other

Link

Pathtraq

loading...