Build small functions from text commands and run a number through them in order.
What to build
A program that applies a pipeline of operations to a starting number and shows each step.
Requirements
- Write
step(command: string): (x: number) => numberfor the commandsadd K,mul K,squareandnegate. - Print
start: X, then for each commandCOMMAND -> VALUE, thenresult: VALUE.
Input
Line 1: the start number. Line 2: m. Then m commands, one per line.
Output
m + 2 lines.
Constraints
0 ≤ m ≤ 20; all values stay below 10^12 in size; commands are valid.
Example
Input:
2
3
add 3
square
negate
Output:
start: 2
add 3 -> 5
square -> 25
negate -> -25
result: -25
Why it works
Returning functions turns each command into a value that can be stored and applied later, and the return type (x: number) => number makes sure every branch gives back something that can be called with a number.
Examples
Example 1 · Input
2 3 add 3 square negate
Expected output
start: 2 add 3 -> 5 square -> 25 negate -> -25 result: -25
Example 2 · Input
7 0
Expected output
start: 7 result: 7
Hints
Hint 1
Write a function step(command: string): (x: number) => number that returns the right function.
Hint 2
Apply the functions in order, printing the value after each.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
function step(command: string): (x: number) => number {
const [name, arg] = command.split(" ");
const k = Number(arg);
if (name === "add") return (x) => x + k;
if (name === "mul") return (x) => x * k;
if (name === "square") return (x) => x * x;
return (x) => -x;
}
let value = Number(read());
console.log("start: " + value);
const m = Number(read());
for (let i = 0; i < m; i++) {
const command = read();
value = step(command)(value);
console.log(command + " -> " + value);
}
console.log("result: " + value);