function makePower(exp) {
return base => base ** exp
}
const square = makePower(2)
const cube = makePower(3)
square(4) // β 16
cube(2) // β 8Closures let the power factory capture the exponent, producing named math functions like square and cube without any duplicate logic.
Create a factory for exponentiation and combine factories to create more complex functions.
Challenge: Create a makePower(exp) function that returns a function. The returned function takes a base and returns base ** exp.
Then, create a makeCompose(fns) function (advanced) that takes an array of functions and returns a new function. When the new function is called with an argument, it passes the argument through each function in sequence, using the output of one as the input to the next.
Example:
const square = makePower(2)
square(5) // 25
const cube = makePower(3)
cube(2) // 8
const addTwo = x => x + 2
const composed = makeCompose([square, addTwo])
composed(3) // square(3) = 9, then 9 + 2 = 11