I'm trying to understand the concept of monads and I want to know if this code is an implementation of this concept (in JavaScript).
I have function M which return new object that have set method which create wrapper method
var foo = M().set('getX', function() {
return this.x;
}).set('setX', function(x) {
this.x = x;
}).set('addX', function(x) {
this.x += x;
});
And then I can chain method of foo
foo.setX(10).addX(20).addX(30).getX()
will return 60
and the same if I have object with methods and call M with this object.
var foo = {
x: 10,
add: function(x) {
this.x += x;
}
};
M(foo).add(10).add(20).add(30).x
will return 70
Functions are wrapped inside M object so the this context inside method is always that M object.
f = M({x: 20}).set('getX', function() {
return this.x;
}).set('addX', function(x) {
this.x += x;
}).addX(10).getX
so f is function with context of object wrapped by M — if I call f()
it will return 30.
Am I understand this correctly? Is M a monad?
EDIT modified code is on github https://github.com/jcubic/monadic