Functional JS with ES6 — Recursive Patterns

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.

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.

Preface

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

Head

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.

https://medium.com/media/fa9e1b667b8a93822c10d9e6665aa860/href

Example usage:

https://medium.com/media/edbf49a35d8efdfd285b3d1003601535/href

Tail

Return all but the first item in an array.

https://medium.com/media/27b247be45a8007c0a88ae5601a71216/href

Which is essentially the same as writing:

https://medium.com/media/a206303f1d78392569bd6d50308681af/href

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:

https://medium.com/media/5c39e93684f5537e638ba3a29eca12d8/href

Def

Return if argument supplied is defined.

https://medium.com/media/040ba009414529ca1ef51f9034d0a50e/href

Example usage:

https://medium.com/media/ae78a0cc63dd95323716100e8f656548/href

Undef

Return if argument supplied is undefined.

https://medium.com/media/274fc2d1201c4511aede669576698bfd/href

Example usage:

https://medium.com/media/b774d356ad9bebfb345fad46dc28e312/href

Copy

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

https://medium.com/media/a05220d00d6188b3a4332d1a5d6aecc2/href

Example usage:

https://medium.com/media/8846a8397c54c0f31fe95317772cf7ff/href

Length

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.

https://medium.com/media/cbcc6a569a86a25144747cc513c3ceaf/href

If we don’t care about tail recursion, we can write it as:

https://medium.com/media/f3769da1c2cc453922ddf794a95be0ef/href

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:

https://medium.com/media/d07eeaaf32ad1c4b5f9e23d8a28a5c86/href

Reverse

Return a reversed array.

https://medium.com/media/ffec0e19c8e0cc4387e7d4331b0c9bfb/href

Example usage:

https://medium.com/media/6a9dc253debc1042561db9bcd3d8df0a/href

Array.reverse() is okay, but it modifies the value in place which is a side-effect. Consider the following:

https://medium.com/media/4736b20279c5c2a1ce1d351e530ad4a6/href

First

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

https://medium.com/media/bfb46d9fbdc8e371228ce3b862765612/href

Example usage:

https://medium.com/media/fda461c7f0aef9f1db5595d6037b26c9/href

Last

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

https://medium.com/media/6166e81381accf14d9440e388010eb78/href

Example usage:

https://medium.com/media/61124a493635a40a66b0a65a902e688e/href

Slice

Returns a new array with value inserted at given index.

https://medium.com/media/e87dbeb028dbf96389b259911e925ae1/href

Example usage:

https://medium.com/media/04be304900e1931cbd8668915d9bed12/href

isArray

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

https://medium.com/media/562f54242767a558c30609114dadf412/href

Example usage:

https://medium.com/media/2f5f174a86158c2499c20b700b5582b6/href

Flatten

Combines nested arrays into a single array.

https://medium.com/media/faede8fd13fac6f010b86b6fd66d99b7/href

Example usage:

https://medium.com/media/730007ad319a7984c5f4c8db2b7d0881/href

Swap

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

https://medium.com/media/2d083f6ce7e4b68f979b1582143d3920/href

Example usage:

https://medium.com/media/65ab8dbe0a8d274cca3b8501155c9d2b/href

Map

From MDN: “…creates a new array with the results of calling a provided function on every element in this array.”

https://medium.com/media/9bf1cd09604134cfa21c6eda9f5cd3bc/href

Which can be simplified as:

https://medium.com/media/57d0119d0fec95fc14871eb9eddb9747/href

Example usage:

https://medium.com/media/744553a44d0d4bfce22c3cf837c7895a/href

Filter

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

https://medium.com/media/671df81580ffe14a5588854d4d567261/href

Which can be simplified as:

https://medium.com/media/5a461c3391feaa1177a8445b0ae15ca7/href

Example usage:

https://medium.com/media/b2b2ecd9a5654534380a2543fd0e8882/href

Reject

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

https://medium.com/media/61231ee883ed67abd605cef23f2cdcb2/href

Example usage:

https://medium.com/media/5eb30b951fc93915b4a0ca5e5b3be67c/href

Partition

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

https://medium.com/media/a03bfa390236b909a38c2cb281bb6093/href

Example usage:

https://medium.com/media/91617720adc5cb40e6ce344365284f85/href

Reduce

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

https://medium.com/media/3ba7ec6ca4a873dd914133ed784e04a7/href

Which can be simplified as:

https://medium.com/media/5f51649e4559abbd9591b2181b17093d/href

Example usage:

https://medium.com/media/04939c45a9c062d19de977f9f905aefc/href

ReduceRight

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

https://medium.com/media/8c0ab13746e0d37fc1bd564c3d1376a9/href

Example usage:

https://medium.com/media/89b053a211612a1dc6d7724caa18f5b0/href

Partial

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

https://medium.com/media/ad2ff9adaf169d8bc2f2211b4a39d62d/href

Example usage:

https://medium.com/media/d5ec4334e1a6c9d6b3dfa611f1856b0f/href

SpreadArg

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

https://medium.com/media/8ca64acfd2db78cfbb7b0c00b5f3da73/href

Example usage:

https://medium.com/media/f608b13000c6b285cccc1ecb2d86fb63/href

If you only want to define a single function you can write it as:

https://medium.com/media/b3382d33cac341170601d03732557575/href

In the above, you need to remember to spread the array you are sending into the function recursively, since you are spreading the argument.

ReverseArgs

Reverse function argument order.

https://medium.com/media/91a2b782a208713a579ba9a2120bfa48/href

Example usage:

https://medium.com/media/ac7227bb135e4b1424da916fa68b10d8/href

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.

https://medium.com/media/0c0b7b7b9b06c23fe4c6c4ac1e283833/href

Pluck

Extract property value from array. Useful when combined with the map function.

https://medium.com/media/a8a6a52d2bef63267e3df6cf3388c22e/href

Example usage:

https://medium.com/media/23af5a17000107015479cd7c165a1582/href

Flow

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

https://medium.com/media/e5c7dcd51930a3c27af48dfeb182c67f/href

Example usage:

https://medium.com/media/3534f90e42ea58a6a6339a73dc9811a5/href

Compose

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:

https://medium.com/media/5e13972791f21bc78d095e48f068453b/href

Example usage:

https://medium.com/media/ef6960fd15dd650cbb6966d6182e3394/href

Min

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

https://medium.com/media/e15d55727c2531ebd7e9b08ed1440e65/href

Example usage:

https://medium.com/media/53589c7e995d763b0a7fc925139dda03/href

Max

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

https://medium.com/media/5484d342bcd2a2340a7b93c46c7e3acc/href

Example usage:

https://medium.com/media/59cbd1f48701634d0d27027974b2cee3/href

Factorial

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

https://medium.com/media/40607d4f1d56fae0bf29d48e7f267008/href

Example usage:

https://medium.com/media/f48517bf8afa63fd4da6c479621291bc/href

Fibonacci

Returns the Fibonacci number at the given place.

https://medium.com/media/574ae7cd22af05d3836ee64a9009b099/href

Example usage:

https://medium.com/media/4e38b546513c353c0c3673193b49fda8/href

Quicksort

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.

https://medium.com/media/ee9f3b2824f84d3cca6bd28bc9b35307/href

This can also be implemented using partition, but requires variable assignment.

https://medium.com/media/6f7508b1dba404839aacb8b4219fc6f0/href

Example usage:

https://medium.com/media/903f808f23b70ee21fe8c86843a8cdf6/href

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.

https://medium.com/media/94f554b0e54e396b6bff4fe980c27de4/href

Example usage:

https://medium.com/media/f9837718a4f1b12e70977701c19b852a/href

Wrapping Up

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.


Functional JS with ES6 — Recursive Patterns was originally published in DailyJS on Medium, where people are continuing the conversation by highlighting and responding to this story.

You may also like...