emmanueltouzery / prelude-ts

Functional programming, immutable collections and FP constructs for typescript and javascript
ISC License
377 stars 21 forks source link

Implement sequenceAcc for Option #57

Closed flakey-bit closed 2 years ago

flakey-bit commented 2 years ago

Would it be possible to implement sequenceAcc for Option? Like you have for Either?

Could be used for validation - let's say you have a bunch of functions that - given some input - perform a validation and return Option<TValidationError> .

You want to apply all of those validation functions and get out an Option<TValidationError[]>. If none of the validation functions produce an error then the outcome would be none.

Something like this:

const optionSequenceAcc = <T>(values: Option<T>[]): Option<T[]> => {
  return values.reduce((accum: Option<T[]>, value: Option<T>) => {
    return value.match({
      None: () => accum,
      Some: (error) => Option.some<T[]>([...accum.getOrElse([]), error])
    })
  }, Option.none())
}
emmanueltouzery commented 2 years ago

sorry for the enormous delay in answering... how would this differ from Option.sequence?

emmanueltouzery commented 2 years ago

right, you'd like that it returns none only if all of the options are none... while sequence returns none if any of the options is none. I don't think about that as accumulating like we're accumulating lefts with either.

i don't know, this doesn't feel like a standard function. I'd say if you need it, you can implement it in your code. maybe if you can find a relatively known library where it's implement, it would change my mind...