Functional JS with ES6 — Recursive Patterns

September 29, 2017 0 Comments

Functional JS with ES6 — Recursive Patterns

 

 

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.

ES6 brings many features that allow us to easily write pure functions, rest/spread being one of the most powerful. Using rest params, we’re able to “loop without loops” with recursion. In this article, we’re going to rewrite many commonly used JavaScript methods/functions that allow for functional patterns.

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.

Example usage:

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.

Example usage:

Return if argument supplied is defined.

Example usage:

Return if argument supplied is undefined.

Example usage:

Returns a copy of an array without using Array.slice(). Makes use of spread.

Example usage:

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”.

Example usage:

Return a reversed array.

Example usage:

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.

Example usage:

Returns a new array that contains the last n items of the given array.

Example usage:

Returns a new array with value inserted at given index.

Example usage:

Returns if the value supplied is an array. Allows us to write Array.isArray() in a more functional manner.

Example usage:

Combines nested arrays into a single array.

Example usage:

Return a new array with 2 items swapped based on their index.

Example usage:

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:

Example usage:

From MDN: “…creates a new array with all elements that pass the test implemented by the provided function.”

Which can be simplified as:

Example usage:

The opposite of filter, returns an array that does not pass the filter function.

Example usage:

Splits an array into two arrays. One whose items pass a filter function and one whose items fail.

Example usage:

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:

Example usage:

Similar to reduce, but applies the function from right-to-left.

Example usage:

Partially apply a function by filling in any number of its arguments.

Example usage:

Convert function that takes an array to one that takes multiple arguments. This is useful when partially applying.

Example usage:

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.

Example usage:

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.

Example usage:

Each function consumes the return value of the function that came before.

Example usage:

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:

Example usage:

Return the smallest number in an array. Returns Infinity if array supplied is empty.

Example usage:

Return the largest number in an array. Returns -Infinity if array supplied is empty.

Example usage:

Returns the factorial of a number. Uses an accumulator to allow replacing of stack frames to allow larger factorials to be returned.

Example usage:

Returns the Fibonacci number at the given place.

Example usage:

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.

Example usage:

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.

Example usage:

I hope this article helps shed insight on some of the patterns made available with JavaScript and ES6. Many problems that can be solved with iteration/loops, can also be solved functionally through recursion. I hope this article was also able to show you the flexibility of the reduce function.


Tag cloud