class Library {
constructor(a){
this.total = a;
}
add(...a){
for (const arg of a) {
this.total += arg;
}
return this;
}
subtract(...b){
for (const args of b) {
this.total -= b;
}
return this;
}
result() {
console.log(this.total);
return this.total
}
}
$ = new Library(10); // inititliaize the base as 10
// var x = $.add(3,5).add(5,10).subtract(10).result;
// x should be 10+3+5+5+10-10 or basically 23
// var y = $.add(3,5).add(5,10).subtract(10,3,5).result to return 15
The problem requires the exact line.
var x = $.add(3,5).add(5,10).subtract(10).result;
The problem requires to chain a method "result" that is not a function I tried
result = function(){
return this.total;
};
Is there a way to return a value in a class without using a function?
3
Answers
Option 1:
You can achieve the expected line format using a getter:
Technically, it’s a function call, but you omit the parenthesis.
Option 2:
You can store the result after each calculation:
In python there is the @property decorator which is really helpul to avoid to call a function and just return the value of the property.
in that case in JS you need to use the get which binds an object property to a function that will be called when that property is looked up.
I’m not sure why you are trying to complicate this, when the obvious answer is to make use of a public class field named result.