Skip to content

Instantly share code, notes, and snippets.

@Jimmydalecleveland
Last active June 26, 2019 18:06
Show Gist options
  • Save Jimmydalecleveland/c6786fa23f4d5f0d3e8aacef5db34514 to your computer and use it in GitHub Desktop.
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
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