-
Consider I want to validate value. Valid value is either empty OR run through validation chain. I know how to validate the value using the chain: (from https://dev.to/gcanti/getting-started-with-fp-ts-either-vs-validation-5eja) import { Either, left, right } from 'fp-ts/Either'
const minLength = (s: string): Either<string, string> =>
s.length >= 6 ? right(s) : left('at least 6 characters')
const oneCapital = (s: string): Either<string, string> =>
/[A-Z]/g.test(s) ? right(s) : left('at least one capital letter')
const oneNumber = (s: string): Either<string, string> =>
/[0-9]/g.test(s) ? right(s) : left('at least one number')
import { chain } from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
const validatePassword = (s: string): Either<string, string> =>
pipe(
minLength(s),
chain(oneCapital),
chain(oneNumber)
) Then I do pipe(
value,
valiDatePassword
) However, I'd like to run Basically trying to write this in FP: const validatePassword = (value: string): bool => ...;
if (value === '') {
return true;
}
return validatePassword(value); Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I was thinking something like this: foldMap validatePassword . guarded (not . null) It doesn't translate nearly as cleanly though: flow(
O.fromPredicate(not(Str.isEmpty)),
O.foldMap(getApplicativeMonoid(E.Applicative)<string, string>(Str.Monoid))(validatePassword),
) You could always just do: x => x === '' ? E.of('') : validatePassword(x), Edit: @gcanti's is better! |
Beta Was this translation helpful? Give feedback.
-
import { fromPredicate, alt } from 'fp-ts/Either'
import { isEmpty } from 'fp-ts/string'
const empty = fromPredicate(isEmpty, () => 'non empty string')
const program = (s: string): Either<string, string> =>
pipe(
empty(s),
alt(() => validatePassword(s))
)
pipe('', program, console.log) // { _tag: 'Right', right: '' }
pipe('aaa', program, console.log) // { _tag: 'Left', left: 'at least 6 characters' } |
Beta Was this translation helpful? Give feedback.
chain
let you combine parsers under an AND condition,alt
let you combine parsers under an OR condition, you could define a parser for empty strings (which could be possibly reused in other circumstances):