hemanth / functional-programming-jargon

Jargon from the functional programming world in simple terms!
http://git.io/fp-jargons
MIT License
18.61k stars 1.02k forks source link

Don't reinvent Array.prototype.flatMap #207

Closed theqp closed 2 years ago

CrossEye commented 3 years ago

The point is that chain is available to any monad. It's part of the JS version of a Monad specification. That there's a shortcut for arrays is useful to know and good to point out, but we can't just say, "Oh, for arrays, use the flatMap method instead." We can't special-case generic implementations for arrays.

We could simply write Array.prototype.chain = Array.prototype.flatMap, but I would rather do that as a comment about an alternative after demonstrating the behavior that's already there.

theqp commented 3 years ago

@CrossEye I have restored chain.

I would rather do that as a comment about an alternative after demonstrating the behavior that's already there.

I am not sure what you meant by that. Having both an implementation with reduce and an alternative that shows ES2019 has flatMap?

CrossEye commented 3 years ago

Perhaps something like this:

// Implementation
Array.prototype.chain = function (f) {
  return this.reduce((acc, it) => acc.concat(f(it)), [])
}

// Alternatively since Array already has an equivalent function: 
//     Array.prototype.chain = Array.prototype.flatMap

I don't think it's necessary, but if there is other worry about duplicating this functionality, then a note might be useful.

jethrolarson commented 3 years ago

Another consideration is that the type signature, while compatible a lot of the time, isn't the same.

Thankfully its closer than Promise.then

jethrolarson commented 2 years ago

While there may be better code to be used I don't think we should take this change. The point is to show how it works and a simple assignment doesn't do that.