I am creating a JavaScript library. I am trying to implement a chain.
0: what I first encountered:
function V(p) { return { add : function(addend) { return V(p + addend); }, sub : function(subtra) { return V(p - subtra); }, }; }
Using this method, I can easily hide the chain:
V(3).add(7).sub(5)
Unfortunately, the result is always a complete V () function, so I cannot extract the resulting value this way. Therefore, I thought a little about this problem and came up with two half-solutions.
1: go to the last method
function V(p, flag) { if(flag) return p; else return { add : function(addend, flag) { return V(p + addend, flag); }, sub : function(subtra, flag) { return V(p - subtra, flag); } }; }
Using this method, I can end the chain by passing the flag to the last method used:
V(3).add(7).sub(5, true)
While this works fine, it requires code repetition and makes the chain less readable, and my code less elegant.
2: Using the start () and end () methods
_chain = false; function V(p) { function Wrap(w) { return (_chain) ? V(w) : w; } return { add : function(addend) { return Wrap(p + addend); }, sub : function(subtra) { return Wrap(p - subtra); }, start : function() { _chain = true; }, end : function() { _chain = false; return p; } }; }
Using this method, you can perform single operations without code:
V(3).add(7)
But the chain requires two more methods, making things much less readable:
V(3).start().add(7).sub(5).end()
So, I'm just looking for the best way to implement chaining in my library. Ideally, I'm looking for something where I can use any number of methods and do not need to interrupt the chain in inelegant ways.
V(3).add(7).sub(5)