Total of an order

Work out the total of an order, and find its most expensive line.

What to build

A program that turns lines of text into objects and then asks questions of the list.

Requirements

  • Each line gives an item, a quantity and a price.
  • A line's cost is its quantity times its price.
  • Print total T, the sum of all the costs.
  • Print dearest NAME, the item with the highest cost. If two items have the same cost, choose the earlier one.

Input

Several lines, each ITEM QTY PRICE.

Output

Two lines.

Constraints

There are from 1 to 50 lines. QTY is from 0 to 1000, and PRICE from 1 to 100000.

Example

Input:

pen 3 10
book 1 250
bag 2 400

Output:

total 1080
dearest bag

Why it works

Once each line is an object, reduce answers one question and sorting answers the other, and neither has to know how the text was laid out. The stable sort handles the rule about ties with no extra code.

Examples

Example 1 · Input
pen 3 10
book 1 250
bag 2 400
Expected output
total 1080
dearest bag
Example 2 · Input
tea 1 5
Expected output
total 5
dearest tea

Hints

Hint 1

First turn each line into an object with map.

Hint 2

reduce adds up qty * price, starting from 0.

Hint 3

Sort a copy by cost, largest first. Sorting is stable, so the earlier of two equal items stays first.

Solution

Show one correct solution (try it yourself first)
const lines = [];
let line = prompt();
while (line !== null) {
  lines.push(line);
  line = prompt();
}
const orders = lines.map((text) => {
  const [item, qty, price] = text.split(" ");
  return { item, cost: Number(qty) * Number(price) };
});
const total = orders.reduce((acc, o) => acc + o.cost, 0);
const dearest = [...orders].sort((a, b) => b.cost - a.cost)[0];
console.log(`total ${total}`);
console.log(`dearest ${dearest.item}`);

Lesson: Array methods: forEach, map, filter and reduce →