Roman and Arabic calculator JavaScript

91 Views Asked by At

I have an assignment on js (Roman and Arabic calculator). As I am not familiar with js, but I have to finish this assignment, I want your help to debug the code and fix my mistakes. I am confused on syntaxis of js and that's why my code looks so messed.

P.S. the problem occurs on the part where I consider Roman numerals Basically, here is how calculator should work:

  1. calculate('1 + 2')->3
  2. calculate('VI / III')->III
  3. calculate('I - II')->" " because there are no negative numbers in roman
  4. calculate('I + 1'->throw Error
  5. calculate('I')->throw Error
  6. calculate('1 + 1 + 1')->throw Error
function romanToInt(s, c) {
  const sym = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
  }

  if (c == 1) {
    const result = 0;
    for (i = 0; i < s.length; i++) {
      const cur = sym[s[i]];
      const next = sym[s[i + 1]];
      if (cur < next) {
        result += next - cur
        i++
      } else
        result += cur
    }
  } else {
    const result = "";
    for (let digit in sym) {
      result += digit.repeat(Math.floor(s / sym[digit]))
      s %= sym[digit]
    }
  }
  return result;
};

function calculator(s) {

  if (s.length <= 1 || !s.trim())
    throw Error;

  let dig_flag = 0,
    rom_flag = 0,
    op_flag = 0;
  let sum = 0;
  let op = 1;
  const stack = [];
  const roman = "IVXLCDM"
  for (let i = 0; i < s.length; i++) {

    if (/[0-9]/.test(s[i])) {
      if (rom_flag == 0) {
        dig_flag = 1;
        let num = 0;
        while ((/[0-9]/.test(s[i])))
          num = num * 10 + +s[i++];
        if (num < 10 && num > 0)
          throw Error;
        else
          stack.push(num);
        i--;
      } else
        throw Error;
    } else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
      if (op_flag == 0) {
        op_flag = 1;
        op = s[i];
      } else
        throw Error;
    } else if (s[i] == ' ')
      continue;

    else if (roman.includes(s[i])) {
      if (dig_flag == 0) {
        rom_flag = 1;
        let num = "";
        while (roman.includes(s[i]))
          num += s[i];
        num = romanToInt(num, 1);
        stack.push(num);
      } else
        throw Error;
    } else
      throw Error;

  }


  if (stack.length == 1)
    return "";
  else if (stack.length > 2)
    throw Error;
  else {
    let fs = stack.pop();
    let sn = stack.pop();
    if (op == '+')
      sum = fs + sn;
    if (op == '-')
      sum = sn - fs;
    if (op == '*')
      sum = fs * sn;
    if (op == '/')
      sum = Math.trunc(sn / fs);
  }
  if (rom_flag == 1) {
    if (sum < 0)
      throw Error;
    else
      return romanToInt(sum, 2);
  }
  return sum.toString();
}

module.exports = calculator;
0

There are 0 best solutions below