Last active
May 25, 2018 12:54
-
-
Save marcog83/2b3c78613593cf1210e71ab660eda74d to your computer and use it in GitHub Desktop.
Validation Create and Compose using 'folktale/validation' library
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
const {Success, Failure} = require('folktale/validation'); | |
const create = (predicate, failure = _ => _) => { | |
return function (value) { | |
if (predicate(value)) { | |
return Success(value) | |
} else { | |
return Failure([failure(value)]); | |
} | |
} | |
}; | |
const compose = (...rules) => { | |
return function (value) { | |
return rules.reduce((prev, curr) => { | |
return prev.concat(curr(value)); | |
}, Success()).map(_ => value); | |
} | |
}; | |
const isPasswordLongEnough = create(password => password.length > 6); | |
const isPasswordStrongEnough = create(password => /[\W]/.test(password), password => `${password} is not strong enough`); | |
var password = "34567890"; | |
const isPasswordValid = compose(isPasswordLongEnough, isPasswordStrongEnough); | |
console.log("isPasswordLongEnough", isPasswordLongEnough(password)); | |
// console.log("isPasswordValid", isPasswordValid(password)); | |
isPasswordValid(password).fold(errors => { | |
console.log("fold KO", errors); | |
}, value => { | |
console.log("fold OK", value) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment