JSFiddle - React, Tailwind, and code Playground

by Guillaume Seguin

JavaScript

'use strict';

function myEval(str) {
  var
    myMath = {
      '+': function(x, y) {
        return x + y;
      },
      '-': function(x, y) {
        return x - y;
      },
      '*': function(x, y) {
        return x * y;
      }
    },
    list = str.match(/\S/g).map(function(e){
      return isNaN(e) ? myMath[e] : Number(e);
    }),
    result = list[0];

  for (var i = 1, maxi = list.length; i < maxi; i+2) {
    result = list[i](result, list[i+1]);
  }
  return result;
}

console.log(myEval('0 + 2'));
console.log(myEval('2 + 1 - 2'));
console.log(myEval('1 + 1 - 1'));
console.log(myEval('2 * 3 - 4 + 1'));