Trying to understand chinning method, can be math like, cheerio/jQuery like, gonna shorten and replace with my own methods when things get too long.
//It will help me get shorten methods in complex methods and apply to a project
function getValue() {
this.add = function(y) {
return x + y;
};
this.mult = function(y) {
return x * y;
};
return this;
};
// not using instance from new operator will interesting
const price1 = getValue(8);
const price2 = getValue(2).add(1);
const price3 = getValue(5).add(3).mult(2);
//not important, but pushing further:
const price4 = getValue().add(2).add(2);
const price5 = getValue(5).add(2).add(2);
console.log(price1); // expect 8
console.log(price2); // expect 3
console.log(price3); // expect 16
console.log(price4); // expect 4
console.log(price5); // expect 9
2
Answers
You need
getValue
to take a parameter ofx
. Also, your chaining functions should returnthis
. Lastly, you need a function to unwrap the value i.e.value()
.Note that in
price4
, you do not pass an initial value, so you can default to0
.Lodash’s
_.chain
works like this:To make your code more re-usable, define top-level methods, ad call them inside the chain:
Here is how to extend jQuery by creating a plugin:
I have improved the above code by add default value to y to prevent the result to "nan" when y is not provided. Overall its a great answer.