gigobyte / purify

Functional programming library for TypeScript - https://gigobyte.github.io/purify/
ISC License
1.5k stars 57 forks source link

EitherAsync's bimap does not behave as the mapLeft for PromiseLike Left values #678

Closed perfectmak closed 6 months ago

perfectmak commented 6 months ago

I recently encountered a difference in the behaviour of the bimap function when applying transformations functions that return a Promise/PromiseLike type.

mapLeft will await the result of a promise and lift that value into the resulting EitherAsync, while bimap lifts default promise without awaiting it.

Here is a sample code to test this out:

// simple identity async function
const asyncMapFn = async (value) => {
    return value
}

async function runMap() {
    EitherAsync(async ({ throwE }) => {
        throwE(new Error("error"))
    })
    .mapLeft(asyncMapFn)
    .caseOf({
        Left: (error) => {
            console.log({ error })
        },
        Right: (value) => {
            console.log({ value })
        },
    })
}

async function runBimap() {
    EitherAsync(async ({ throwE }) => {
        throwE(new Error("error"))
    })
    .bimap(asyncMapFn, asyncMapFn)
    .caseOf({
        Left: (error) => {
            console.log({ error })
        },
        Right: (value) => {
            console.log({ value })
        },
    })

}

await runMap()
await runBimap()

This will messages similar to:

Object {error: Error: error}
Object {error: Promise (resolved)}

I'm happy to contribute a solution to this behaviour but want to know if this is intended.

gigobyte commented 6 months ago

Hello! This is not intended, the behaviour should be the same and map/mapLeft are the correct ones. In fact, this is a bugfix that was made for map but I forgot to change bimap 😅

I welcome any incoming PRs for this, otherwise I will fix it myself at the start of the next year.

perfectmak commented 6 months ago

I have some downtime this weekend and I'll work on a fix and open a PR.

perfectmak commented 6 months ago

I just opened a PR #680 to fix this issue. Let me know what you think.