Last active
June 26, 2019 18:06
-
-
Save Jimmydalecleveland/c6786fa23f4d5f0d3e8aacef5db34514 to your computer and use it in GitHub Desktop.
Example of a way to compose a chain of methods conditionally for libraries that use method chaining
This file contains 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 compose = funcObjects => startingInstance => | |
funcObjects.reduce( | |
(composed, currentFunc) => | |
composed[currentFunc.method](currentFunc.argument), | |
startingInstance | |
); | |
// Example of how compose would be called with static data | |
// const emailComposed = compose( | |
// { method: "email", argument: "Enter an email, tallywacker." }, | |
// { method: "required", argument: "I AM Required Message." }, | |
// )(Yup.string()) | |
const data = [ | |
{ | |
htmlName: "email", | |
fieldType: "string", | |
validations: [ | |
{ requiredType: "email", errorMessage: "EMAIL DUMMY" }, | |
{ requiredType: "required", errorMessage: "I AM required Message." } | |
] | |
} | |
]; | |
const composeValidation = (type, validations) => { | |
const formattedForComposition = validations.map(validation => { | |
return { | |
method: validation.requiredType, | |
argument: validation.errorMessage | |
}; | |
}); | |
return compose(formattedForComposition)(Yup[type]()); | |
}; | |
// Yup.string().email().required("message") | |
const validationSchema = data.reduce((acc, cur) => { | |
acc[cur.htmlName] = composeValidation(cur.fieldType, cur.validations); | |
return acc; | |
}, {}); | |
// Which is used like so: | |
Yup.object().shape(validationSchema) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment