Concise JavaScript abusing replacements


  • 0
    var calculate = function(s) {
        return s.replace(/-/g, '+-').split('+').reduce((sum, s) => sum + mult(s), 0);
    };
    
    function mult(s) {
        let ops = '*' + s.replace(/[\d -]+/g, '');
        if (ops.length === 1) return parseInt(s);
        return s.split(/[*\/]/g).reduce((a, b, i) => ops[i] === '*' ? a * b : (a ^ b) > 0 ? ~~(a / b) : -~~(-a / b), 1);
    }
    

    And here's the production version (kidding):

    let m = (s, o) => (o = '*' + s.replace(/[\d-]/g, ''), s.split(/[*\/]/g).reduce((a, b, i) => o[i] === '*' ? a * b : a * b > 0 ? ~~(a / b) : -~~(-a / b), 1));
    let calculate = s => s.replace(/-/g, '+-').split('+').reduce((t, s) => t + m(s), 0);
    

    A similar approach for the first Basic Calculator is found here.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.