Is there any way to make a function's return accessible via a property?

偶尔善良 提交于 2019-12-02 18:28:11

问题


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 written.

For example:

function square (num) {
  return num * num;
}
let foo = 2 
let a = square(foo) //=> 4
let b = square(square(foo)) //=> 16

Fair enough, but what I'd like to do (often to make code parsing easier) is to chain together those methods by passing that in as the first parameter of a chain. So that something like this would work:

let c = square(foo)
          .square()
          .square() //=> 256

Is there any way to do this with vanilla javascript, or is this something I'd have to modify the Function.prototype to do?


回答1:


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



回答2:


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());



回答3:


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



回答4:


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);


来源:https://stackoverflow.com/questions/44105026/is-there-any-way-to-make-a-functions-return-accessible-via-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!