Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Closure and currying magic for cleaner javascript

DZone's Guide to

Closure and currying magic for cleaner javascript

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

Sometimes you find a piece of javascript, a perfect piece of javascript, it does exactly what you need! Perfect! You could spend hours, even days, getting something to work and someone’s already done it, shared the code on the internets even!

Hooray!

But … the code looks something like this:

// to populate later
var data = [], oldData = [], semiOldData = [];
var a_switch = "blah";
 
function do_something() {
   // use subset of globals
}
 
function something_else() {
   // use some other globals
}
 
// etc.
 
function update() {
  // use all of the above
}

The code works … if you only need to use it once. What if you need two independent widgets? Well, you could take the time to recode all of that so it becomes purely functional.

But that’s going to be a problem – the code heavily relies on state. Ok maybe object oriented? Object oriented kind of sucks in javascript and you’d have to recode all of that, have to perfectly understand it etc.

Pain in the arse!

Closure magic

There’s a better way – put it in a closure.

var my_widget = (function (data_function) {
// to populate later
var data = [], oldData = [], semiOldData = [];
var an_index = 1;
 
function do_something() {
   // use subset of globals
}
 
function something_else() {
   // use some other globals
}
 
// etc.
 
function update(index) {
  an_index = index;
  data = data_function();
  // use all of the above
}
 
return update;
});

Now you get to create the widget with a simple function call. Hooray!

And the function returns its own update function so you can run an update whenever you need. All the state and weirdness is neatly packaged inside the closure, the code itself doesn’t need to know anything about the outside state.

By changing the update function a little bit you can even affect the internal state of the closure by calling the curried function.

Closures upon closures

Here’s where it gets even more magical. Stacking closures to achieve true greatness.

Code is the best way to explain what I mean …

// these functions are used to slice up data
var slice_functions = {
        students: function (item) { return !!item.cs_student; },
        others: function (item) { return !item.cs_student; },
        everyone: function (item) { return true; }
    },
        slice_func = slice_functions.students,
 
// these functions provide cleaned up data
// all must use the same main slice_func
        data_functions = {
            year_vs_pay: function (year) {
                var data = DATA.filter(slice_func).filter(function (item) {
                    return item.years_study == year;
                }),
                // ...
                return fin_data;
            },
            study_vs_pay: function (study) {
                var data = DATA.filter(slice_func).filter(function (item) {
                    return item.study_time == study;
                }),
                // ...
                return fin_data;
            },
            // ...

Those are our data functions, when creating new widgets we can provide them as the data_function argument shown above.

Now comes the tricky part – we can externally change the slice_func and all the data_functions (now safely tucked inside closures) change their behaviour by using the new slice_function since variables inside closures are pointers rather than copies.

Magic!

We have reached a situation where all code is tucked neatly inside closures. The closures themselves have no knowledge of the outside world, there are no flags they need to check, no external data anywhere. All they care about is running the data function and doing their thing.

And yet, through the magic of closures, we get to globally change their behaviour without worrying about internal state or having to call a specific function to do something on an object.

To me this feels cleaner than any abstraction object oriented programming has ever come up with.

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}