Skip to content

Instantly share code, notes, and snippets.

@dmi3y
Created August 3, 2015 10:06
Show Gist options
  • Select an option

  • Save dmi3y/824a64d25eb3946016a1 to your computer and use it in GitHub Desktop.

Select an option

Save dmi3y/824a64d25eb3946016a1 to your computer and use it in GitHub Desktop.

Revisions

  1. dmi3y created this gist Aug 3, 2015.
    50 changes: 50 additions & 0 deletions calc.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    function calcFromStr(str) {
    var ops = ['*','/','+','-'];
    var reg = /(\b\D)/;
    var calc = str.split(reg);

    function calculator(l, op, r) {

    switch( op ) {
    case '*':
    return l*r;
    case '/':
    return l/r;
    case '+':
    return l+r;
    case '-':
    return l-r;

    }

    }

    calc.forEach(function(el, ix) {

    if ( ix % 2 === 0 ) {

    calc[ix] = Number(el);
    }
    });

    do {
    var op = ops.shift();
    var ix;
    var nval;


    do {
    ix = calc.indexOf(op);

    if ( ix > 0 ) {

    nval = calculator(calc[ix - 1], op, calc[ix + 1]);
    calc.splice(ix-1, 3, nval);
    }

    } while ( ix > -1 );

    } while( ops.length );

    return calc[0];
    }