Home > Enterprise >  how to save and then store a calculated value from a function calculation, inside an array
how to save and then store a calculated value from a function calculation, inside an array

Time:01-07

I cannot stress the question more than this thread's header! I am trying to save a previously calculated sum from a function, into an empty array that I have created afterward (outside of the function's scope).

how can i save all calculated sums into one array instead of only pushing the element that is calculated into the array and the next time there is a new element, and the previous one is deleted and not saved.

also!! i want to know if i have written the task correctly and used the function tool correctly!

Steven is still building his tip calculator, using the same rules as before: Tip 15% of the bill if the bill value is between 50 and 300, and if the value is different, the tip is 20%. Your tasks:

  1. Write a function 'calcTip' that takes any bill value as an input and returns the corresponding tip, calculated based on the rules above (you can check out the code from first tip calculator challenge if you need to). Use the function type you like the most. Test the function using a bill value of 100
  2. And now let's use arrays! So create an array 'bills' containing the test data below
  3. Create an array 'tips' containing the tip value for each bill, calculated from the function you created before
  4. Bonus: Create an array 'total' containing the total values, so the bill tip Test data: 125, 555 and 44 Hint: Remember that an array needs a value in each position, and that value can actually be the returned value of a function! So you can just call a function as array values (so don't store the tip values in separate variables first, but right in the new array)

my code:

myBills = [125, 555, 44, 57, 683, 12, 991, 33, 477, 28, 1215];
const billCalc = Math.floor(Math.random() * myBills.length);
const randomBill = myBills[billCalc];
let tipValue = undefined;
if (randomBill >50 && randomBill <300) {
    tipValue = 15;
}
else if (randomBill <50 || randomBill >300) {
    tipValue = 20;
}
let finalTip = tipValue / 100 * randomBill;

function calcTip(tip) {
    if (tipValue === 15) {
        console.log(`The bill for the table is ${randomBill}, 
        and the tip is : ${finalTip}.
         The final payment is: ${randomBill   finalTip}`);
    }
        
    else if (tipValue === 20) { // change the rquality operator to 2 or 3
        console.log(`The bill for the table is ${randomBill}, 
        and the tip is : ${finalTip}.
         The final payment is: ${randomBill   finalTip}`);
    }

}

// this supposed to save the results for the tips, and to store it in the array below this line.

const tipSave = calcTip(finalTip);

const tipList = [21, 22, 63]
tipList.push(tipSave);

if there is anything u can teach me from my code, what I did wrong, and how I could have simplified it, make it more clean, or things I have used and should not have used.

also about the array question. I would very much like to get help regarding this.

CodePudding user response:

Looking at what's been written....

// myBills = [125, 555, 44, 57, 683, 12, 991, 33, 477, 28, 1215];
// it's a good habit to declare things that shouldn't change as const
const myBills = [125, 555, 44, 57, 683, 12, 991, 33, 477, 28, 1215];

It's good that you wrote a test...

const billCalc = Math.floor(Math.random() * myBills.length);
const randomBill = myBills[billCalc];

...but, the next bit is the logic being tested, and you were asked to write that in functional form. It seems to be the point of the whole exercise, so moving your code into a function and tweaking it a little...

function calcTip(amt) {
    let tipValue; // don't need = undefined;, that's the default
    // the question is unclear whether these are >= and <=
    // the norm is inclusive on the low end, exclusive on the high
    if (amt >= 50 && amt <300) { 
        tipValue = 15;
    }
    else {
     // we don't need to spell out the alternative with else if 
     // and the alternative you spelled out:
     // <50 || >300 misses edge cases when the amount is 50 or 300

        tipValue = 20;
    }
    let finalTip = tipValue / 100 * amt;
    return finalTip;
}

It's just as correct and almost as easy to read to compress all that as follows:

function calcTip(amt) {
  const tipValue = amt >= 50 && amt < 300 ? 0.15 : 0.20;
  return tipValue * amt;
}

Now we can write your test...

console.log(`the tip for ${randomBill} is ${calcTip(randomBill)}`)

Check this by inspection and a hand calculation.

Applying to array in JS is easy. You just need to learn about map().

array.map(function)

Map takes a single parameter (function) and applies that function to every element of array, returning an array of whatever the function returned for each element.

That's just what you need. Your array is myBills, and your function is calcTip, so:

const tips = myBills.map(calcTip);
console.log(tips)

Bonus: the total function can use the calcTip function straight-forwardly

function calcTotal(amt) {
    return amt   calcTip(amt);
}

const totals = myBills.map(calcTotal;
console.log(totals);

Most people are in the habit of coding the function param to map inline. This is a sort of deeper topic, but be aware that we could have skipped creating the calcTotal function and just written this:

const totals = myBills.map((amt) => {
  return amt   calcTip(amt);
});

or, more tersely...

const totals = myBills.map(amt => amt   calcTip(amt));

In summary:

const myBills = [125, 555, 44, 57, 683, 12, 991, 33, 477, 28, 1215];

function calcTip(amt) {
  const tipValue = amt >= 50 && amt < 300 ? 0.15 : 0.20;
  return tipValue * amt;
}

const tips = myBills.map(calcTip);
console.log(tips)

const totals = myBills.map(amt => amt   calcTip(amt));
console.log(totals)

CodePudding user response:

I am trying to save a previously calculated sum from a function, into an empty array that I have created afterward

I'm sorry, I'm not sure if I'm understanding this correctly as I don't see any empty arrays in your code, however I will take the liberty of assuming that the array you want to add elements to is tipList.

how can i save all calculated sums into one array instead of only pushing the element that is calculated into the array and the next time there is a new element, and the previous one is deleted and not saved.

By using yourArrayName.push(), elements are appended to the end of the array, and the elements already in the array remain unchanged.

Write a function 'calcTip' that takes any bill value as an input

Your function calcTip() takes an argument "tip" as an input. It is usually better to name the argument with reference to the input it represents, "bill" perhaps.

I'm not quite sure what you're trying to get at with your code, so I'll make a few suggestions:

  • the else if line is not necessary as you are just testing for the opposite of the if condition, the else keyword will suffice
  • putting the calculation of the tip outside of the function is not advisable as the tip will be a constant for subsequent calls of calcTip(), put it in the function instead to get accurate tipping rates
  • calcTip() takes the tip argument but the value is not used anywhere in the function, whereas static values calculated outside of the function are used instead. There is no problem with using these static values, however the tip argument should be used to make your function more "applicable" to different input values

I made a few changes to your code and added some comments for your understanding, and included some references at the bottom for more information on the methods and keywords I used

myBills = [125, 555, 44, 57, 683, 12, 991, 33, 477, 28, 1215];
const billCalc = Math.floor(Math.random() * myBills.length);
const randomBill = myBills[billCalc];

function calcTip(bill) {
    // function which gives us the tip based on the instructions, we define this function below
    const percent = getMultiplier(bill);
    
    // calculation of the tip ( bill x tip% )
    const finalTip = bill * percent / 100;
    console.log(`The bill for the table is ${bill}, 
    and the tip is : ${finalTip}.
    The final payment is: ${bill   finalTip}`);
    return finalTip; // this line gives tipSave the value of the finalTip at line 29
}

// this function which tests if the argument "bill" is within the range of 50 < bill < 300
// If it is within the range, it returns 15, otherwise, it returns 20
function getMultiplier(bill) {
    if (bill > 50 && bill < 300) {
        return 15;
    } else {
        return 20;
    }
}

// this supposed to save the results for the tips, and to store it in the array below this line.

const tipSave = calcTip(randomBill);

const tipList = [21, 22, 63];
tipList.push(tipSave);
console.log(tipList); // prints the array of tips to the console

Some references

  • Related