Ad
Code
Diff
  • const yearlyElectricCosts = (...monthCosts) => parseFloat(monthCosts.reduce((a, b) => a + b, 0).toFixed(2));
    • /*input data come from parameters with zero default value, so it can calculate for any data and can be tested with different test cases*/
    • const yearlyElectricCosts = (m1 = 0, m2 = 0, m3 = 0, m4 = 0, m5 = 0, m6 = 0, m7 = 0, m8 = 0, m9 = 0, m10 = 0, m11 = 0, m12 = 0 ) => {
    • /* Create an object with 12 keys and the input values*/
    • const monthlyCosts = {
    • januaryBill : m1,
    • februaryBill : m2,
    • marchBill : m3,
    • aprilBill : m4,
    • mayBill : m5,
    • juneBill : m6,
    • julyBill : m7,
    • augustBill : m8,
    • septemberBill : m9,
    • octoberBill : m10,
    • novemberBill : m11,
    • decemberBill : m12
    • }
    • /*print the object*/
    • console.log(monthlyCosts);
    • // Decide on a variable name and sum all the monthly charges
    • const totalCharges = Object.values(monthlyCosts).reduce((acc, curr) => acc + curr, 0);
    • // Return the value of the variable by typing it in after the `return` keyword below
    • console.log(totalCharges.toFixed(2), typeof(totalCharges.toFixed(2)));
    • /*toFixed converts the result to string, we have to convert it back to number*/
    • return parseFloat(totalCharges.toFixed(2));
    • }
    • const yearlyElectricCosts = (...monthCosts) => parseFloat(monthCosts.reduce((a, b) => a + b, 0).toFixed(2));