I\'m a JS dev, experimenting with functional programming ideas, and I\'m wondering if there\'s anyway to use chains for synchronous functions in the way the promise chains are w
It is really a bad idea to modify Function.prototype
or Number.prototype
because you will pollute the default JavaScript objects, say: what if other framework also do the evil and add their own square
?
The recommended way is to make an object by your self.
function num(v) {
this.v = v;
this.val = function() { return this.v; };
this.square = function() { this.v = this.v * this.v; return this; };
//and you can add more methods here
this.sqrt = function() { this.v = Math.sqrt(this.v); return this; };
return this;
}
var n = new num(2)
console.log(n.square().square().sqrt().val());
You can set square
and num
as a property of square
call`
function square (num) {
if (!this.square) {
this.square = square;
this.num = num || 0;
};
if (num === undefined) {
this.num *= this.num
}
else if (!isNaN(num)) {
this.num *= num;
};
return this;
}
let foo = 2;
let c = new square(foo).square().square();
console.log(c.num);
You might be interested in the Identity functor – it allows you to lift any function to operate on the Identity's value – eg, square
and mult
below. You get a chainable interface without having to touch native prototypes ^_^
const Identity = x => ({
runIdentity: x,
map: f => Identity(f(x))
})
const square = x => x * x
const mult = x => y => x * y
let result = Identity(2)
.map(square)
.map(square)
.map(square)
.map(mult(1000))
.runIdentity
console.log(result)
// 256000
You wouldn't have to modify Function.prototype, but Number.prototype. You're trying to create a new method that acts on a number, not on a function. This does what you're trying to do:
Number.prototype.square = function() {
return this * this;
}
let x = 4;
let y = x.square().square(); // -> 256