Reputation: 29
I was asked in an interview to solve
init(1).add(2).mul(3).div(4).val();
Output it should achieve this functionality, I am more concerned about how to call in the above way
(1 + 2) * 3 / 4 = 2.25
How can we implement it using javascript? I thought of creating functions with nested function, whats the correct way?
I did
var gmap = function(num) {
this.x = num;
this.add = function(ad) {
this.x = this.x * ad;
return this;
}
this.del = function(de) {
this.x = this.x + de;
return this;
}
this.final = function() {
return this.x;
}
}
Upvotes: 1
Views: 886
Reputation: 3936
If you don't want to use an instance of a class, you can make use of closures:
function init(start) {
// this is the starting value that will get updated with each function call
let value = start;
// This is the object to be returned, notice that seach return the object instance
let self = {
add: num => {
value += num;
return self;
},
sub: num => {
value -= num;
return self;
},
mul: num => {
value *= num;
return self;
},
div: num => {
value /= num;
return self;
},
val: () => {
return value;
}
};
return self;
}
init(1).add(2).mul(3).div(4).val(); // 2.25
Essentially, each time the init function is called a new closure-scope is created. Within this scope, new instances of any local variables that are created and only accessible within that scope.
When the init function is called, two new variable instances are created value
and self
that are only accessible to other 'things' created in the init function.
With each of those functions, we return the variable that contains the function-set which is how its able to chain calls.
Upvotes: 1
Reputation: 193
You can do something like this using builder pattern (ES6):
function init(value) {
this.result = value;
return {
add: function(addValue) {
this.result = this.result + addValue;
return this;
},
mul: function(mulValue) {
this.result = this.result * mulValue;
return this;
},
div: function(divValue) {
this.result = this.result / divValue
return this;
},
val: function() {
return this.result;
},
result: this.result,
};
}
init(1).add(2).mul(3).div(4).result
Upvotes: 0
Reputation: 4945
You can do it using class
style too
class Chainable{
init(num){
this.total = num;
return this;
}
add(num){
this.total += num;
return this;
}
}
using it like so
var c = new Chainable();
c.init(1).add(1);
Upvotes: 3