Skip to content

Instantly share code, notes, and snippets.

@raveclassic
Last active October 12, 2017 23:07
Show Gist options
  • Save raveclassic/e68e1f5016ca3f6b05dc8510c75f9a13 to your computer and use it in GitHub Desktop.
Save raveclassic/e68e1f5016ca3f6b05dc8510c75f9a13 to your computer and use it in GitHub Desktop.
validation vs either
import { Either, left, right, either } from './Either'
import { constant } from './function'
import { Validation, failure, success, validation } from './Validation'
import { array, traverse } from './Array'
type TValidation<A> = Validation<string[], A>
const fail = <L, A>(error: L): Validation<L[], A> => failure(array)([error])
const belowZero = (n: number): TValidation<number> => (n < 0 ? success(n) : fail('GTE zero'))
const aboveFive = (n: number): TValidation<number> => (n > 5 ? success(n) : fail('LTE five'))
const validate = <T>(checks: Array<(value: T) => TValidation<T>>) => (value: T): TValidation<T> =>
traverse(validation)(f => f(value), checks).map(constant(value))
const validateAll = validate([belowZero, aboveFive])
console.log(validateAll(3))
console.log(validateAll(0))
console.log(validateAll(5))
//
type TEither<A> = Either<string, A>
const belowZeroE = (n: number): TEither<number> => (n < 0 ? right(n) : left('GTE zero'))
const aboveFiveE = (n: number): TEither<number> => (n > 5 ? right(n) : left('LTE five'))
const validateE = <T>(checks: Array<(value: T) => TEither<number>>) => (value: T): TEither<T> =>
traverse(either)(f => f(value), checks).map(constant(value))
const validateAllE = validateE([belowZeroE, aboveFiveE])
console.log(validateAllE(3))
console.log(validateAllE(0))
console.log(validateAllE(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment