0
function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type === "food") {
      total += items[i].price * 1.1;
    } else {
      total += items[i].price;
    }
  }
  return total;
}

const items = [
  { type: "food", price: 10 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

console.log(calculateTotal(items));

I need to improve on this code.

I have tried improving the variable description. here is the code again with improved variables

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.type === "food") {
      total += item.price * 1.1;
    } else {
      total += item.price;
    }
  }
  return total;
}

const items = [
  { type: "food", price: 10 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

console.log(calculateTotal(items));

what else can i try improving on in this code?

1 Answers1

0

You can add a factor const with shorted if syntax for better readability

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    const factor = (item.type === "food") ? 1.1 : 1
    total += item.price * factor;
  }
  return total;
}

const items = [
  { type: "food", price: 10 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

console.log(calculateTotal(items));

Or using forEach JavaScript syntax you can use:

function calculateTotal(items) {
  let total = 0;
  items.forEach((item) => {
    total += ((item.type === "food") ?  item.price * 1.1 : item.price) 
    })
  return total;
}

Also, you can add factor property inside the item object itself to 'special' items (with factor != 1) like this:

const items = [
  { type: "food", price: 10, factor: 1.1 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

Than you can use the reduce method like this:

function calculateTotal(items) {
  let total = items.reduce((acc, item) => {
    return acc + item.price * (item?.factor || 1)
    }, 0)
  return total;
}

Or just:

function calculateTotal(items) {
  return items.reduce((acc, item) => {
    return acc + item.price * (item?.factor || 1)
    }, 0)
}
Daniel Agam
  • 209
  • 1
  • 9