Search code examples
javascriptfunctional-programminglanguage-featuresfunction-prototypes

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


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?


Solution

  • 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