Hide a running total inside a module.
What to build
A score object made with the module pattern, whose total nothing can change directly.
Requirements
- Complete the immediately called function. It keeps a private number that starts at 0.
- It returns an object with
add(n), which adds to the number, andtotal(), which returns it. - The rest of the program is in the starter, and also prints whether the data is really hidden.
Input
Several lines: add N or total.
Output
One line for each total command. The last line is hidden: true when no private value can be reached through the object.
Constraints
There are from 1 to 50 commands. N is a whole number from -1000 to 1000.
Example
Input:
add 5
add 2
total
Output:
7
hidden: true
Why it works
The variable belongs to a function that has already finished, so no outside code can name it. add and total are closures, and they are the only way in.
Examples
Example 1 · Input
add 5 add 2 total
Expected output
7 hidden: true
Example 2 · Input
total
Expected output
0 hidden: true
Hints
Hint 1
Inside the function, declare let total = 0.
Hint 2
Return an object holding add and total functions.
Hint 3
{ add, total } is a short way to write { add: add, total: total }.
Solution
Show one correct solution (try it yourself first)
const score = (function () {
let sum = 0;
function add(n) {
sum += n;
}
function total() {
return sum;
}
return { add, total };
})();
let line = prompt();
while (line !== null) {
const [command, n] = line.split(" ");
if (command === "add") {
score.add(Number(n));
} else {
console.log(score.total());
}
line = prompt();
}
console.log(`hidden: ${Object.keys(score).join() === "add,total"}`);