Last active
October 24, 2018 21:07
-
-
Save hisapy/c255ef694c616fa8509919501fdef249 to your computer and use it in GitHub Desktop.
"Imperative" vs Functional Javascript example
This file contains 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
/* | |
Given props routeIndices such as [0, 2, 2, 4] and routes such as [RouteObj, RouteObj] passed to a React component, | |
use the routeIndices to traverse down the routes tree, via RouteObj children, to get the RouteObj title attribute. | |
For example, a <Route title="Home" /> from Found. | |
*/ | |
getTitleFromRouteImperative() { | |
const { routeIndices, routes } = this.props; | |
let currentRoute = routes[routeIndices[0]]; | |
for (let i = 1; i < routeIndices.length; i += 1) { | |
const currentRouteIndex = routeIndices[i]; | |
currentRoute = currentRoute.children[currentRouteIndex]; | |
} | |
return currentRoute.title; | |
} | |
getTitleFromRouteFunctional() { | |
const { routeIndices, routes } = this.props; | |
const currentRoute = routeIndices.reduce((prevRoute, currentIndex) => { | |
if (prevRoute === null) { | |
return routes[currentIndex]; | |
} | |
return prevRoute.children[currentIndex]; | |
}, null); | |
return currentRoute.title; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment