DEV Community

Discussion on: Daily Challenge #45 - Change Machine

Collapse
 
aminnairi profile image
Amin • Edited

Hey there, thank you for your comment!

Don’t get me wrong, I like your version, but in the strict sense I’d argue it isn’t more “pure” than the original version.

We might think that the COINS variable declared with a const operator is indeed a constant but it is not. It is not possible to assign another array, but you can still update its values by targeting its indexes. This means that the function is inpure because its result is not predictable as it relies on an out-scope variable that can be updated outside of the function call, but used inside the function. The oustide world can update the array like so:

COINS[0] = "Hello world!";

The solution would be to declare the array as a freezed array in JavaScript:

const COINS = Object.freeze([1, 2, 3, ...]);

That way, no side-effects possible. This would also allow the function to be pure again. Another solution would be to declare the COINS variable inside the function, or even better, declare another parameter if the coins variable is something to be changed later.

const change = (cents, COINS = [1, 2, 3, ...]) => ...