Calculator – adding math function – theOdinProject

  Kiến thức lập trình

Per the Odin Project’s instructions, I need to make my basic calculator operate via math functions rather than using eval(). https://www.theodinproject.com/lessons/foundations-calculator

I’ve only added the addition part to my mathWorks function. However, I’m not sure how to tie my mathWorks function to my else if block when “=” is selected. Any help would be greatly appreciated.

const container = document.querySelector(".container");
const calcBody = document.querySelector("#calcBody");
const input = document.querySelector("#input");
let a = "";
let b = "";
let operator = "";
let result = "";


      
const numbers = {
    reset: "CE",
    goBack: "C",
    divide: "/",
    multiply: "*",
    seven: 7,
    eight: 8,
    nine: 9,
    add: "+",
    four: 4,
    five: 5,
    six: 6,
    minus: "-",
    one: 1,
    two: 2,
    three: 3,
    decimal: ".",
    zero: 0,
    equal: "=",
};

for (let key in numbers) {
    let button = document.createElement("button");
    button.setAttribute("id", key);
    button.textContent = numbers[key];
    container.appendChild(button);

    button.addEventListener("click", (e) => {
        let val = e.target.textContent;
       
        if(e.target.textContent === "+" || 
           e.target.textContent === "/" ||
           e.target.textContent === "*")
           {
           operator = val;
           input.textContent = a + " " + operator + " ";
           }

        else if(e.target.textContent === "CE") {
             input.textContent = "";
             a = "";
        }
        else if(input.textContent.includes("*") ||
                 input.textContent.includes("+")  ||
                 input.textContent.includes("/")) {
            b += val;
            input.textContent = a + " " + operator + " " + b;
        }

        else if(e.target.textContent === "="){
            mathWorks();
            }
        
        
            else 
        {
            a += val
            input.textContent = a;
        }

    });

    function mathWorks(){
        if(operator === "+"){
            result = parseFloat(a) + parseFloat(b);
            input.textContent = result;
            
        }

    }

}

I’ve tried adding my a + b parameters. Adding parseFloat. Truly, I’m kind of at a loss.

LEAVE A COMMENT