'Javascript Closures Exercise
Got this exercise from school:
Implement the calculate function that returns an object that gives the ability to perform the four mathematical operations (sum, subtraction, multiplication, and division) on the same number and finally prints the result.
TIP: To concatenate the methods just return the reference to the object itself ($this)
Example:
calculator .add(2) // 2 .add(4) // 6 .multiply(3) // 18 .sub(1) // 17 .sub(3) // 14 .divide(2) // 7 .printResult();
What I did:
function calculate() {
let result = 0;
let calculator = {
add: function(number) {
return result += number;
},
multiply: function(number) {
return result *= number;
},
sub: function(number) {
return result -= number;
},
divide: function(number) {
return result /= number;
},
printResult: function() {
return result;
}
}
return calculator;
}
const calculator = calculate();
calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // The result will be: 7
Please help me I know it's wrong but I did not understand closures with objects. Also give me explanations.
Solution 1:[1]
The calculator methods add, multiply...etc should return the calculator object (which is this), not the result. So with a minor modification, it will work
function calculate() {
let result = 0;
let calculator = {
add: function(number) {
result += number;
return this;
},
multiply: function(number) {
result *= number;
return this;
},
sub: function(number) {
result -= number;
return this;
},
divide: function(number) {
result /= number;
return this;
},
printResult: function() {
return result;
}
}
return calculator;
}
const calculator = calculate();
let result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult();
// The result will be: 7
console.log(result);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
