Write a function that builds other functions.
What to build
A function makeAdder(n) that returns a function which adds n to whatever it is given.
Requirements
- Read n from the first line.
- Make one adder with
makeAdder(n). - For each later line, print the result of calling the adder with that number.
Input
The first line is n. Each later line is a number.
Output
One line for each number after the first.
Constraints
There are from 1 to 50 numbers after n. All are whole numbers from -1000 to 1000.
Example
Input:
5
1
2
Output:
6
7
Why it works
makeAdder has already returned by the time the adder is used, yet the adder still knows n. That memory of the surrounding variables is exactly what a closure is.
Examples
Example 1 · Input
5 1 2
Expected output
6 7
Example 2 · Input
-1 10
Expected output
9
Hints
Hint 1
makeAdder takes n, and returns a new function.
Hint 2
The inner function takes x, and returns x + n.
Hint 3
The inner function can use n because it remembers where it was created.
Solution
Show one correct solution (try it yourself first)
function makeAdder(n) {
return (x) => x + n;
}
const add = makeAdder(Number(prompt()));
let line = prompt();
while (line !== null) {
console.log(add(Number(line)));
line = prompt();
}