Skip to content

Instantly share code, notes, and snippets.

@hisapy
Last active October 24, 2018 21:07
Show Gist options
  • Save hisapy/c255ef694c616fa8509919501fdef249 to your computer and use it in GitHub Desktop.
Save hisapy/c255ef694c616fa8509919501fdef249 to your computer and use it in GitHub Desktop.
"Imperative" vs Functional Javascript example
/*
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