Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanDalkvist/0a36974d763f2e73737311584c3d6ffe to your computer and use it in GitHub Desktop.
Save VanDalkvist/0a36974d763f2e73737311584c3d6ffe to your computer and use it in GitHub Desktop.
import React from "react";
const renderDefinition = definition => props =>
definition && definition.Component ? (
<definition.Component {...props} />
) : null;
const renderFirst = definitions => props => {
const definition = definitions.find(definition =>
definition.condition(props)
);
return renderDefinition(definition)(props);
};
const newBuilder = () => {
const definitions = [];
return {
with: function addConditionalComponent(condition, Component) {
definitions.push({ condition, Component });
return this;
},
build: renderFirst(definitions),
buildFirst: renderFirst(definitions),
buildAll: props => {
return definitions
.filter(definition => definition.condition(props))
.map(definition => renderDefinition(definition)(props));
}
};
};
const conditionalBuilder = () => {
const ifBuilder = newBuilder();
function elseBranch(Component) {
return {
build: props => {
const result = ifBuilder.buildFirst(props);
return result || renderDefinition({ Component })(props);
}
};
}
return {
if: function ifBranch(condition) {
return {
then: Component => {
ifBuilder.with(condition, Component);
return { else: elseBranch };
}
};
}
};
};
export { newBuilder, conditionalBuilder };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment