// 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');
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.