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

后端 未结 4 1215
小鲜肉
小鲜肉 2021-01-27 03:30

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

4条回答
  •  终归单人心
    2021-01-27 03:58

    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

提交回复
热议问题