One scope, more closures

JavaScript uses closure as an elegant way to hide a function internal status the rest of the world. It is simple to extend the concept and let more closures share the same variables.

My original sequence generator had its status defined as a property, and as such visible by everybody who had access to the function itself. I decided that was bad, and I refactored it as a closure. Cool, but the client programmer needs to modify the sequence internal status, to be able to skip ahead of a few numbers when needed.

To achieve this result, we need to do a substantial change to our code:
var sequence = (function() {
    var current = 0;
    return { // 1
        get: function() { // 2
            return current++;
        },
        skip: function(delta) { // 3
            if(delta > 0) // 4
                current += delta;
        }
    }
}());
1. The external anonymous function does not return anymore a single function, but an object containing a couple of properties, that happens to be functions.
2. The first property is named get, and it actually is our old sequence generator.
3. Here is the required improvement, a function named skip that changes the sequence generator internal status.
4. I didn't provide much error handling to the code, but I couldn't help to put at least this line, meant to avoid the user to move the sequence back and forth.

A use test for the new sequence:
for(var i = 0; i < 3; ++i)
    console.log(sequence.get()); // 1
sequence.skip(3); // 2
for(var i = 0; i < 3; ++i)
    console.log(sequence.get());
1. Get each time a new sequence number, starting from zero.
2. Skip three numbers in the sequence, before getting more numbers.

No comments:

Post a Comment