Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add flat and flatMap methods to Maybe functor #13

Merged
merged 1 commit into from
Jan 10, 2024

Conversation

ortense
Copy link
Owner

@ortense ortense commented Jan 10, 2024

description

Add flat and flatMap methods to Maybe functor

.flat

A method to removing one level of nesting, if applicable.

const data = maybe(maybe('data')) //? Maybe<Maybe<string>>

const flatted = data.flat() //? Maybe<string>

const nonNestedFlatted = flatted.flat() //? Maybe<string> 

.flatMap

Useful to combine functions that returns Maybe

const divide = (denominator: number) =>
  (numerator: number) => denominator === 0
    ? maybe(null) : maybe(numerator/denominator)

const getFromLocalStorage = (key: string) =>
  maybe(localStorage.getItem(key))

When a function returns a Maybe

getFromLocalStorage('count') //? Maybe<string>
  .map(Number) //? Maybe<number>
  .map(divide(2)) //? Maybe<Maybe<number>>

getFromLocalStorage('count') //? Maybe<string>
  .map(Number) //? Maybe<number>
  .flatMap(divide(2)) //? Maybe<number>

When needs to map a nested Maybe

getFromLocalStorage('count') //? Maybe<string>
  .map(Number) //? Maybe<number>
  .map(divide(2)) //? Maybe<Maybe<number>>
  .flatMap(value => value + 1) // Maybe<number>

@ortense ortense merged commit 2cb1f53 into main Jan 10, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant