A Few Concepts
“Always look for simple repeatable actions that can be abstracted out into a function."
- Functions must accept at least one argument.
- Functions must return either data or another function.
- Loops are bad. Use recursion instead. (No dirty looks, now.)
Immutability and Statelessness
Statelessness means that your function should not need to know what happened before the function is used or afterwards.
Here is a brief example that gathers the total of values in an array. Note: the example follows the rules that I mentioned earlier.
Notice that we broke out the function ‘addNumbers’. This simple operation now becomes a reusable function and helps to keep our code DRY. Also, take note that we are not mutating the array that was passed in, rather we are recursively stepping through the array to gather our total value.
Higher Order Functions
Currying is a way to construct functions that will allow partial application of a function’s arguments. You can pass in all of the arguments a function expects and get a result, or you can pass a subset of arguments and get a function back that’s waiting for the rest of the arguments.
As you can see in the example above the function ‘yumCurry’ actually returns another function that takes a separate argument. We can pass as many parameters as we like, creating custom variations of our original curried function. This can become powerful and keeps things readable as well.