Created
June 4, 2018 10:42
-
-
Save VanDalkvist/0a36974d763f2e73737311584c3d6ffe to your computer and use it in GitHub Desktop.
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
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