r/functionalprogramming • • Dec 19 '23

JavaScript Monads in JavaScript

23 Upvotes

11 comments sorted by

View all comments

Show parent comment

2

u/sultan-naninine Dec 20 '23 edited Dec 28 '23

I am happy to join your chat, not to debate, but to learn about the pros and cons of different development approaches. Regarding the "avoiding boilerplate" feature, I have also considered ways to make it more elegant. I call it placeholders, and I used Proxy to track all deep chains.

const parseUserName = json => flow(json)
  .then(JSON.parse)
  .then(P.name) // user => user.name
  .then(R.trim()) // name => name.trim()
  .catch(() => 'n/a')
  .then(R.toUpperCase())  // str => str.toUpperCase()
  .finally()

Here is the implementation of the placeholders.

const propertyProxy = f => new Proxy(f, {
  get: (_, key) => {
    const g = x => f(x)[key]
    return propertyProxy(g)
  }
})

const methodProxy = f => new Proxy(f, {
  get: (_, key) => {
    const g = (...args) => x => f(x)[key](...args)
    return methodProxy(g)
  }
})

const P = propertyProxy(x => x)
const R = methodProxy(x => x)

I would like to combine R with P to have one placeholder to use this way: P.users.at(0).name.toUpperCase(), but I have not yet found a solution for that.