What’s the deal here?
Functional programming has been on the rise and is a topic that is very exciting to me. It allows me to write terse, declarative code that is easy to test and reason about. What is functional programming? I’ll defer that answer to someone with more knowledge on the subject, Eric Elliot:
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data,and side-effects. Functional programming is declarative rather than imperative, and application state flows through pure functions. Contrast with object oriented programming, where application state is usually shared and colocated with methods in objects.
The following functions are for demonstration and learning purposes. Many functions below are tail-recursive and should be optimized further. Fixing tail-recursion is not the subject of this article. ES6 brings tail-call optimization, but must be used in conjunction with
'use strict' .
Return the first item in an array. Is useful when you need to separate the first item from the rest of the array items. To do this, we make use of destructuring assignment.
Return all but the first item in an array.
Which is essentially the same as writing:
Since we don’t need to use
x in the returned output, we can drop it, but keep the comma to get the rest of the items in the array.
Return if argument supplied is defined.
Return if argument supplied is undefined.
Returns a copy of an array without using
Array.slice(). Makes use of spread.
Return the length of an array. This is a very simple form of looping through an array with recursion, even though the values of the array don’t matter in this case (increments up starting at 1 for every item in array). We include the len param to avoid tail recursion.
If we don’t care about tail recursion, we can write it as:
This would add a stack frame for each item in the array, whereas the version that avoids tail recursion, replaces a single stack frame. If the array passed in is large enough, it will throw “Maximum call stack size exceeded”.
Return a reversed array.
Array.reverse() is okay, but it modifies the value in place which is a side-effect. Consider the following:
Returns a new array that contains the first n items of the given array.
Returns a new array that contains the last n items of the given array.
Returns a new array with value inserted at given index.
Returns if the value supplied is an array. Allows us to write
Array.isArray() in a more functional manner.
Combines nested arrays into a single array.
Return a new array with 2 items swapped based on their index.
From MDN: “…creates a new array with the results of calling a provided function on every element in this array.”
Which can be simplified as:
From MDN: “…creates a new array with all elements that pass the test implemented by the provided function.”
Which can be simplified as:
The opposite of filter, returns an array that does not pass the filter function.
Splits an array into two arrays. One whose items pass a filter function and one whose items fail.
From MDN: “…applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.”
Which can be simplified as:
Similar to reduce, but applies the function from right-to-left.
Partially apply a function by filling in any number of its arguments.
Convert function that takes an array to one that takes multiple arguments. This is useful when partially applying.
If you only want to define a single function you can write it as:
In the above, you need to remember to spread the array you are sending into the function recursively, since you are spreading the argument.
Reverse function argument order.
Reversing arguments can be useful when partially applying arguments. Sometimes you want to partially apply arguments at the end of the list, not those at the beginning. Reversing the arguments allows us to do that.
Extract property value from array. Useful when combined with the map function.
Each function consumes the return value of the function that came before.
The same as flow, but arguments are applied in the reverse order. Compose matches up more naturally with how functions are written. Using the same data as defined for the flow function:
Return the smallest number in an array. Returns Infinity if array supplied is empty.
Return the largest number in an array. Returns -Infinity if array supplied is empty.
Returns the factorial of a number. Uses an accumulator to allow replacing of stack frames to allow larger factorials to be returned.
Returns the Fibonacci number at the given place.
Sort an array from smallest to largest. This is done by re-ordering the array so that it contains two sub-arrays, one with smaller values, the other with larger values. The above steps are recursively applied to each sub-array until there are no arrays left, which is flatten to return a sorted array.
This can also be implemented using partition, but requires variable assignment.
Everything as a Reduction
Many of the functions above can be converted into reductions, which should increase performance in most, if not all cases. This also shows the flexibility of the reduce function.
Feedback? Words of encouragement? 🎉
I’m glad you made it! I’m always looking to improve my articles, if you would like to leave feedback (I would love it if you did!) you can find the Google Form here. It’s very short, I promise!