Chapter 2 - stateless/pure functions

by Denise Nepraunig

HTML

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>

JavaScript

// Programming JavaScript Applications
// Chapter 2
// stateless/pure functions

/*  a stateless or pure functions always returns the same value for a given input and doesn't change outside variables */

/* this stateless/pure feature is very useful because you have to handle a lot of asynchronous events, so therefore time becomes a major factor in code organization */

/* stateless is therefore better scaleable accros a large number of worker nodes -> great for high-concurrency applications.

stateless functions can be abstracted and shared as context-agnostic modules */

// here is a non-pure example
var rotate = function rotate(arr) {
    // shift removes the first element and returns it
    arr.push(arr.shift());
    return arr;
};

QUnit.test('Rotate non-pure', function(assert) {
    var original = [1, 2, 3];
    
    assert.deepEqual(rotate(original), [2,3,1],
                     'rotate() should rotate array elements.');
    
    // Fails!!! Original array gets mutated
    assert.deepEqual(original, [1,2,3],
                     'should not mutate external data');
    
});

// here is the pure example
var safeRotate = function safeRotate(arr) {
    // slice cuts out pieces, but doesn't change the original array
    var newArray = arr.slice(0);
    newArray.push(newArray.shift());
    return newArray;
};

QUnit.test('Rotate pure', function(assert) {
    var original = [1, 2, 3];
    assert.deepEqual(safeRotate(original), [2,3,1],
                     'rotate() should rotate array elements.');
    
    // Passes, external array is not changed
    assert.deepEqual(original, [1,2,3],
                     'should not mutate external data');
    
});