In Abstracting services with closures I showed how you could get more functional by using closures. Curried functions are another approach to encapsulating values in a function – minimizing the number of arguments and variables you need to carry around in your functions.

This is a very simple example that shows how a more functional approach could be applied to working with Properties services.

Why curry ?

I’m not sure why it’s called currying*, but let’s stick with the theme for the example. Imagine you had this to do

* update – it’s named for Haskell Curry after whom the Haskell language is named. Thanks to for pointing it out.

Everywhere in your App, you’d need to know which Properties service you were using, and the property name you’d be saving that against. If instead that could be encapsulated in a function, you would only need to know the function name – so you’d be doing this instead.

Of course, there are many ways of doing this, but using currying allows you to reuse the same functions to create other similar curried functions. That doesn’t mean anything till we get to some examples, so let’s dive in.

First currying function

This takes an argument of the Properties service to use (Script, Document, User), but doesn’t yet actually do anything aside from returning another function which itself takes arguments of propertyName and value, and it’s only when this second function is executed that anything happens.

Using currying functions

Well, we can do this – see if you can figure out what’s happening.

but since the point is to encapsulate stuff, we’ll do this – here’s a different curried function for each of the property services

And then we can use them like this

// now each of the curried scripts embeds the properties service to use

Using curried functions

Let’s go a bit further. We’ve decided that we want to be able to just say this anywhere in the App.

and if we decide to change the service or propertyname, all that can be done just by changing the currying functions – so in other words, the current setScript function needs to have the curryType property encapsulated.

Here’s the new currying function

and it can be used like this, to make our desired curryType function

Now we can just do this

If we want to enhance the property service handling (for example by using exponential backoff, dealing with objects, or even using a database instrad of a property store, all that can be done in a single currying function.

And that’s a wrap for this introduction to currying. If you want more, ping me on the community.

For more like this see Google Apps Scripts Snippets

Why not join our community , follow the blog or follow me on Twitter