Last active
July 10, 2018 04:12
-
-
Save toddmantell/05e7ac293acc8046714d92ab8953e9fb to your computer and use it in GitHub Desktop.
Refactoring Ryan's Nested Ternaries into Clean Functions
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
| // Original logic for reference: | |
| component ? ( // component prop gets first priority, only called if there's a match | |
| match ? React.createElement(component, props) : null | |
| ) : render ? ( // render prop is next, only called if there's a match | |
| match ? render(props) : null | |
| ) : children ? ( // children come last, always called | |
| typeof children === 'function' ? ( | |
| children(props) | |
| ) : !Array.isArray(children) || children.length ? ( // Preact defaults to empty children array | |
| React.Children.only(children) | |
| ) : ( | |
| null | |
| ) | |
| ) : ( | |
| null | |
| ) | |
| //My version, refactored | |
| const returnValidElementComponentPropsOrChildren = () => { | |
| if (component) { | |
| return returnComponentIfThereIsARouteMatch(match); | |
| } | |
| else if (render) { | |
| return executeRenderPropOnRouteMatch(render, props); | |
| } | |
| else if (children) { | |
| return returnRenderedChildrenIfTheyAreFunctionsOrNotAnArray(children, props); | |
| } | |
| else return null; | |
| } | |
| function returnComponentIfThereIsARouteMatch(match) { | |
| if (match) return React.createElement(component, props); | |
| else return null; | |
| } | |
| function executeRenderPropOnRouteMatch(render, props){ | |
| if (match) render(props) | |
| else return null; | |
| } | |
| function returnRenderedChildrenIfTheyAreFunctionsOrNotAnArray(children, props) { | |
| if (typeof children === 'function') { | |
| return children(props); | |
| } | |
| else | |
| { | |
| if (!Array.isArray(children) || children.length) { | |
| return React.Children.only(children); | |
| } | |
| else return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment