dwyl / learn-tdd

:white_check_mark: A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
Mozilla Public License 2.0
2.74k stars 349 forks source link

Functional Solution #109

Closed nelsonic closed 6 years ago

nelsonic commented 6 years ago

Can we write a purely functional solution to get beginners used to the idea of writing functional code?

nelsonic commented 6 years ago

Helpful links:

nelsonic commented 6 years ago
const COINS = [200, 100, 50, 20, 10, 5, 2, 1]; // "constant" of all coins

function getChange (payable, paid) {
  return COINS.reduce((change, coin) => {
    const change_sum = change.reduce((sum, coin) => sum + coin, 0);
    const remaining = paid - payable - change_sum;
    const times_coin_fits = Math.floor(remaining / coin);
    return change.concat(Array(times_coin_fits).fill(coin));
  }, []); // change array starts out empty and gets filled itteratively.
}

I don't think Array.fill is "purely functional" because it mutates the array in-place, but I can't think of how else to do it ... 🤔