Coding Academy / Exercise

Turn raw data into useful results

Build a small data pipeline with map, filter and reduce. Handle empty input instead of guessing the happy path.

You will learn to

  • Transform values without mutating input
  • Explain the empty-list result
  • Use checks to find edge cases

Before you start

JavaScript arrays and functions

One transformation at a time

Here an order is a number of rupees. The result is the total of positive orders after a ten percent discount. Filter invalid orders before applying the discount. Reducing an empty array without an initial accumulator throws; start at zero so the empty case is intentional.

Reason about the result

For [100, -5, 200], ignore -5. The remaining amounts become 90 and 180, so the total is 270. Repeated rounding changes totals. In financial production code use integer minor units and a defined rounding policy. This exercise uses whole-number inputs so you can focus on transformations.

Try, inspect, explain

Implement discountedTotal below. Add console.log calls to inspect each stage. A check is evidence for a particular input, not proof for every input. Explain why an empty list returns zero and why the original array should stay unchanged.

Try it yourself

function discountedTotal(orders) {
  // Filter positive orders, discount by 10%, then sum.
  return 0;
}
console.log(discountedTotal([100, -5, 200]));

Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.

Continue exploring