Evaluate dice rolling notation strings

前端 未结 14 1429
甜味超标
甜味超标 2021-01-30 14:55

Rules

Write a function that accepts string as a parameter, returning evaluated value of expression in dice notation, including addition and multiplication.

To

14条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 15:20

    JavaScript solution, 340 chars when compressed (no eval, supports prefixed multiplicator and suffixed addition):

    function comp (s, m, n, f, a) {
        m = parseInt( m );
        if( isNaN( m ) ) m = 1;
        n = parseInt( n );
        if( isNaN( n ) ) n = 1;
        f = parseInt( f );
        a = typeof(a) == 'string' ? parseInt( a.replace(/\s/g, '') ) : 0;
        if( isNaN( a ) ) a = 0;
        var r = 0;
        for( var i=0; i

    Test code:

    var test = ["3d6 + 12", "4*d12 + 3", "d100"];
    for(var i in test)
        alert( test[i] + ": " + parse(test[i]) );
    

    Compressed version (pretty sure you can do shorter):

    function c(s,m,n,f,a){m=parseInt(m);if(isNaN(m))m=1;n=parseInt(n);if(isNaN(n))n=1;f=parseInt(f);a=typeof(a)=='string'?parseInt(a.replace(/\s/g,'')):0;if(isNaN(a))a=0;var r=0;for(var i=0;i

提交回复
热议问题