function makeCountdown(from) {
let n = from
return () => (n > 0 ? n-- : 0)
}
const cd = makeCountdown(3)
cd() // β 3
cd() // β 2
cd() // β 1
cd() // β 0The countdown closure holds its own private counter, decrementing on each call and clamping at zero to prevent negative values.
Create a function that counts down from an initial value until it reaches 0, then stays at 0.
Challenge: Create a makeCountdown(from) function that returns a function. Each call decrements and returns the current value, starting at from and never going below 0.
Example:
const countdown = makeCountdown(3)
countdown() // 3
countdown() // 2
countdown() // 1
countdown() // 0
countdown() // 0