After reading about currying, partial application and other functional programming techniques, some developers are left wondering when, exactly, they would ever use those methods; and why would they want to?

With this three part blog post series we'll try to tackle that issue and show how you could approach solving a problem in a functional fashion in the context of a small, realistic example.

What is Functional Programming

Before we dive right in, let's take a brief moment to review some practical functional programming concepts.

Functional programming focuses on the "function" as the primary expression of reuse. By building small functions that focus on very specific tasks, functional programming uses composition to build up more complex functions - this is where techniques like currying and partial application come into play.

Functional Programming uses functions as the declarative expression of reuse, avoiding mutating state, eliminating side effects & using composition to build functionality

Functional programming is essentially programming with functions! The additional considerations like avoiding mutating state, pure functions with no side effects and elimination of loops in favor of recursion are part of a Pure Functional Programming approach, which is built in in languages like Haskell.

We'll focus on the practical parts of functional programming that we can immediately make use of in Javascript in this blog series.

Higher Order Functions - Javascript has first-class functions, which means we can pass functions as arguments to other functions; and return functions as values from functions.

Decorators - Because we can make higher order functions, we can create functions that augment other functions' behavior and/or arguments

Composition - we can also create functions that are composed of multiple functions, created chained processing of inputs.

We'll introduce the techniques we'll use to take advantage of these features as they are needed. This lets us introduce them in context and keep the concepts digestible and easy to understand.

Let's Build Something, Already!

Ok, so what is it we are going to build?

Let's take the typical example of needing to process some data coming back from an asynchronous request. In this case, the response is in JSON format and contains a list of blog post summaries.

Here's our response data we'll be working with: View full data in Gist and an example record.

// An example record from our JSON response data
var records = [  
    "id": 1,
    "title": "Currying Things",
    "author": "Dave",
    "selfurl": "/posts/1",
    "published": 1437847125528,
    "tags": [
      "functional programming"
    "displayDate": "2015-07-25"
  // ...

Our Requirements: Now, suppose that we want to build a display of recent posts (no older than a month), organized in groups by tags and sorted by publish date. Let's think for a moment about what we need to do:

  • filter out posts older than a month (say, 30 days).
  • group the posts by their tags (this might mean posts show up in two groups if they have more than one tag.)
  • sort each tag listing by published date, descending.

We'll cover each requirement above in a single post in this series, starting with filtering in this post.

Filtering the Records

Our first step is to filter out the records where the published date is older than the last 30 days. Since functional programming is all about functions as the primary expression for reuse, let's build a function to encapsulate the act of filtering a list.

function filter(list, fn) {  
  return list.filter(fn);

I can hear you asking now..., "Really? That's all!?"

Well, yes, and no.

While this function encapsulates the concept of filtering an array (list) using a predicate function (fn), which could have easily been done by just calling list.filter(fn) directly. So, why not do it that way?

Because when we abstract the operation into a function, we can then use currying to build a more useful function.

Currying is the act of taking a function with N arguments and returning a nested series of N functions that each take 1 argument.

For more information and to brush up on this concept, read my previous post about currying and an implementation of left->right currying.

In this case we'll use a function called rightCurry(), which curries a function's arguments from right to left. Typically, a plain curry() function would curry arguments left to right.

Here's our implementation, along with another utility function flip(), which it uses internally.

// Returns a function which reverses the order of the 
// arguments to the passed in function when invoked.
function flip(fn) {  
    return function() {
        var args = [];
        return fn.apply(this, args.reverse());

// Returns a new function that curries the original 
// function's arguments from right to left.
function rightCurry(fn, n) {  
  var arity = n || fn.length,
      fn = flip(fn);
  return function curried() {
      var args = [], 
          context = this;

      return args.length >= arity ?
          fn.apply(context, args.slice(0, arity)) : 
          function () {
              var rest = [];
              return curried.apply(context, args.concat(rest));

With currying we can create functions that allow us to create new, partially applied functions we can reuse. In our case, we'll use it to create a function which partially applies a predicate to the operation of filtering a list.

// A function to filter a list with a given predicate
var filterWith = rightCurry(filter);  

This is basically the same as manually currying our binary filter(list, fn) function like this.

function filterWith(fn) {  
  return function(list) {
    return filter(list, fn);

And we can use it as follows?

var list = [1,2,3,4,5,6,7,8,9,10];

// Create a partially applied filter to get even numbers from a list
var justEvens = filterWith(function(n) { return n%2 == 0; });

// [2,4,6,8,10]

Wow, seems like a lot of work initially; but what we got out of this approach is

  • using currying to create a general, reusable function, filterWith(), which can be used in a number of situations to create more specific list filters
  • the ability to execute this new filter lazily whenever we get some data. We can't call Array.prototype.filter without having it act on a list of data immediately
  • a more declarative API that aids in readability and understanding

About that Predicate Function

Our filterWith() function needs a predicate function, which returns true or false when given an item in the list, to determine if that item should be returned in the newly filtered list.

Let's start off by making a more generic comparison function that can tell us if a given number is greater than or equal to another number.

// Simple comparison for '>='
function greaterThanOrEqual(a, b) {  
  return a >= b;

Given that our published dates are in numeric, timestamp format (milliseconds since the Epoch) this should work fine. But, the predicate function for filtering Arrays is only passed a single argument to check, not two.

So, how do we make our binary comparison function work in a situation that needs a unary function?

Currying to the rescue again! We'll use it to make a function that can create unary comparison functions.

var greaterThanOrEqualTo = rightCurry(greaterThanOrEqual);  

We can now use this curried version to create a unary predicate function that will work with list filtering, such as:

var list = [5,3,6,2,8,1,9,4,7],  
    // a unary comparison function to see if a value is >= 5
    fiveOrMore = greaterThanOrEqualTo(5);

// [5,6,8,9,7]

Awesome! Now we can be more specific and create a predicate that solves our original problem of filtering dates greater than or equal to 30 days ago:

var thirtyDaysAgo = (new Date()).getTime() - (86400000 * 30),  
    within30Days = greaterThanOrEqualTo(thirtyDaysAgo);

var dates = [  
  (new Date('2015-07-29')).getTime(), 
  (new Date('2015-05-01')).getTime() 

// [1438128000000]  - July 29th, 2015

So far, so good!

We've created a predicate for filtering that can be easily reused. Also, because we're using a functional approach, our code is much more declarative and easy to follow - it sort of reads exactly as it works. Readability and maintenance are important things to consider when writing any code!

Type Problems...

Uh-oh, we have another issue! Our program needs to filter a list of objects, so our predicate function is going to need to access the published property on each item passed in.

Our current predicate, within30Days(), doesn't handle object argument types, only scalar values! Let's solve that with another function! (are you seeing a pattern here?)

We'd like to reuse our existing predicate function; but modify its arguments so that it can work with our specific object types. Here's a new utility function that let's us augment an existing function by modifying its arguments.

function useWith(fn /*, txfn, ... */) {  
  var transforms = [], 1),
      _transform = function(args) {
        return, i) {
          return transforms[i](arg);
  return function() {
    var args = [],
        targs = args.slice(0, transforms.length),
        remaining = args.slice(transforms.length);

    return fn.apply(this, _transform(targs).concat(remaining));

This is our most interesting functional utility so far, and nearly identical to the function of the same name in the Ramda.js library.

useWith() returns a function which modifies the original function, fn, so that when it is invoked, it will pass each argument through a corresponding transform (txnfn) function. If there are more arguments when invoked than transform functions, the remaining arguments will be passed in "as is."

Let's help that definition out with a small example. Simply, useWith() lets us do the following:

function sum(a,b) { return a + b; }  
function add1(v) { return v+1; }  
var additiveSum = useWith(sum, add1, add1);

// Before sum receives 4 & 5, they are each passed through
// the 'add1()' function and transformed
additiveSum(4,5);  // 11  

When we call additiveSum(4,5) we essentially get the following call stack:

  • additiveSum(4,5)
    • add1(4) => 5
    • add1(5) => 6
    • sum(5, 6) => 11

We can use useWith() to modify our existing predicate to operate on object types rather than scalar values. First, let's use currying again to create a function that lets us create partially applied functions that can access objects by property name.

// function to access a property on an object
function get(obj, prop) { return obj[prop]; }  
// Curried version of `get()`
var getWith = rightCurry(get);  

Now we can use getWith() as the transform function to grab the .published date from each object to pass to our unary predicate function used in the filter.

// Our modified predicate that can work on the `.published` 
// property of our record objects.
var within30Days = useWith(greaterThanOrEqualTo(thirtyDaysAgo), getWith('published'));  

Let's give this a try with some test data:

// Array of sample object data
var dates = [  
      { id: 1, published: (new Date('2015-07-29')).getTime() }, 
      { id: 2, published: (new Date('2015-05-01')).getTime() }
    within30Days = useWith(greaterThanOrEqualTo(thirtyDaysAgo), getWith('published'));

// Get any object with a published date in the last 30 days
// { id: 1, published: 1438128000000 }

Ready to Filter!

Ok, given our first requirement to keep only post records within the last 30 days, let's give our full implementation a run with our response data.

// [
//    { id: 1, title: "Currying Things", displayDate: "2015-07-25", ... },
//    { id: 2, title: "ES6 Promises", displayDate: "2015-07-26", ... },
//    { id: 7, title: "Common Promise Idioms", displayDate: "2015-08-06", ... },
//    { id: 9, title: "Default Function Parameters in ES6", displayDate: "2015-07-06", ... },
//    { id: 10, title: "Use More Parenthesis!", displayDate: "2015-08-26", ... },
// ]

We now have a new list of just posts within the last 30 days. Looks like we've met our first requirement and are off to a good start. As we go along, we'll put our functional utilities in a library that we can reuse.

Get the Source: You can see the source code for this post, which has all our functional utilities in a single .js file and our main application logic in its own file as well. We'll continue to add to these in each post in this series.


We've discovered some key functional programming techniques like currying and partial application and the contexts in which we can use them. We also found out that focusing on building small, useful functions in conjunction with functional techniques allows us to compose higher order functions and enable better reuse. With these basics under our belt, the next two posts will seem much less daunting.

In the next post in this series we'll combine what we have so far for filtering with grouping the records by tag name, where we'll introduce more list related functions and more flexible function composition as well.