Last active
February 28, 2018 15:31
-
-
Save fabriziomoscon/3f9349d7881d5e28c8f5e90f3d0ab0b0 to your computer and use it in GitHub Desktop.
checking the validity of collectionVolume in a functional way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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