Skip to content

Instantly share code, notes, and snippets.

@fkhadra
Created May 16, 2017 21:18
Show Gist options
  • Save fkhadra/70ec7995a4211c674c2361e638d81fce to your computer and use it in GitHub Desktop.
Save fkhadra/70ec7995a4211c674c2361e638d81fce to your computer and use it in GitHub Desktop.
export function withConditionalRequire(fn, msg = null) {
fn.isRequiredIf = function (cb) {
if (typeOf(cb) !== 'Function') {
return new Error(`\`withConditionalRequire\` expect first argument
to be a valid callback. ${typeOf(cb)} given.
`);
}
return function (props, propName, componentName) {
if (cb(props, propName, componentName)) {
const prop = props[propName];
if (typeof prop === 'undefined') {
let errorMsg;
switch (typeOf(msg)) {
case 'Function':
errorMsg = msg(props, propName, componentName);
break;
case 'String':
errorMsg = msg;
break;
}
return typeOf(errorMsg) === 'String'
? new Error(errorMsg)
: new Error(`The prop ${propName} is marked as required in
${componentName}, but its value is undefined.`);
}
}
return checkPropTypes({ [propName]: fn }, props, propName, componentName);
};
};
return fn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment