I just wanted to show the community a different way to program that has really helped cleanup my codebase and make it more simple. More experienced programmers will already know this but since OO programming is so prevalent I think it’s worth mentioning.
Example 1 - Simplify with partial application
(also a great example of how JS closures work)
We’ll create a function with the arguments we’d like to pass in then that function returns a new function. The inner function will have access to the outer function’s variables which allows us to pass in our component and still use the params and queryParams arguments in FlowRouter. Notice, render
is getting called because we use the ()
to call and return the new function for FlowRouter.
// create a cleaner API by 'preloading' arguments for 'action'
function render(Comp, Layout = MainLayout) {
return function action(params, queryParams) {
ReactLayout.render(Layout, {
content: <Comp store={store} />
});
};
}
FlowRouter.route('/about', {name: 'About Page', action: render(AboutPage) } );
FlowRouter.route('/login', {name: 'Login Page', action: render(LoginPage) } );
Instead of this:
FlowRouter.route('/about', {name: 'About Page', action: aboutActionFn } );
actionFn(params, queryParams) {
ReactLayout.render(MainLayout, {
content: <AboutPage store={store} />
});
}
FlowRouter.route('/login', {name: 'Login Page', action: loginActionFn } );
loginActionFn(params, queryParams) {
ReactLayout.render(MainLayout, {
content: <LoginPage store={store} />
});
}
### Using many simple functions instead of one complex one:
Take a common example… formatting a phone number to a normalized format. The imperative approach would be to make a single function with conditionals that does 4 different things at once. In larger examples this can be very complex. Also I realize one regex could replace this but that’s not the point for a simple example
Here’s one way to do it in a functional approach that’s similar to Unix pipes, sending one result to the next function:
cleanNum = pipe("(123) 456-7890")
.removeSpaces()
.removeParens()
.removeDashes()
.value()
// or without the piping helper you can unpack this from the middle to outward:
removeDashes(removeParens(removeSpaces("(123) 456-7890")))
#### code to do this with underscore: ``` // gives underscore's chain a better API pipe = _.chain;
removeDashes = function(str) {
return str.replace(/-/g, ‘’);
};
removeParens = function(str) {
return str.replace(/(|)/g, ‘’);
};
removeSpaces = function(str) {
return str.replace(/\s/g, ‘’);
};
// allow these to be chained with underscore
_.mixin({
removeSpaces: removeSpaces,
removeParens: removeParens,
removeDashes: removeDashes
});
Interested? Checkout these guides/ebooks for JavaScript
- 1 http://eloquentjavascript.net/1st_edition/chapter6.html
- 2 Free Ebook https://github.com/MostlyAdequate/mostly-adequate-guide