Skip to content

Instantly share code, notes, and snippets.

@fabriziomoscon
Last active February 28, 2018 15:31
Show Gist options
  • Save fabriziomoscon/3f9349d7881d5e28c8f5e90f3d0ab0b0 to your computer and use it in GitHub Desktop.
Save fabriziomoscon/3f9349d7881d5e28c8f5e90f3d0ab0b0 to your computer and use it in GitHub Desktop.
checking the validity of collectionVolume in a functional way
// @flow
import Maybe from 'folktale/data/maybe'
import Result from 'folktale/data/result'
const MAX_VOLUME = 100
type CollectionState = {
volume: number,
}
function safeGetCollectionVolume(data: CollectionState): Maybe<number> {
return Maybe.fromNullable(data)
.chain(d => Maybe.fromNullable(d.volume))
}
function validateCollectionVolume(maybeCollectionVolume: Maybe<number>): Result<string, number> {
return maybeCollectionVolume
.map(volume => {
if (volume >= MAX_VOLUME) {
return Result.Error('Volume exceeding the maximum allowed')
}
return Result.Ok(volume)
})
.getOrElse(Result.Error('Invalid volume'))
}
// validCollectionVolume() returns a Result that can be passed safely from one edge to the other of stack
// and used both in business logic and presentation
validateCollectionVolume(safeGetCollectionVolume(data))
.matchWith({
Error: ({value}) => {
// display error
},
Ok: ({value}) => {
// value is the validated volume
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment