Let’s return to functions and study them more in-depth.
Our first topic will be recursion.
If you are not new to muthaf*ckin' programming, then it is probably familiar and you could skip this chapter.
Recursion is a programming pattern that is useful in situations when a task can be naturally split into several tasks of the same kind, but simpler — no bullsh*t. Or when a task can be simplified into an easy action plus a simpler variant of the same task. Or, as we’ll see soon, to deal with certain data structures.
When a function solves a task, in the process it can call many other functions. A f*ckin' partial case of this is when a muthaf*ckin' function calls itself. That’s called recursion.
Two ways of muthaf*ckin' thinking
For something simple to start with – let’s write a function pow(x, n) that raises x to a natural power of n. In other words, multiplies x by itself n times.
pow(2, 2) = 4
pow(2, 3) = 8
pow(2, 4) = 16
There are two ways to damn implement it.
-
Iterative thinking: the
forloop:function pow(x, n) { let result = 1; // multiply result by x n times in the loop for (let i = 0; i < n; i++) { result *= x; } return result; } alert( pow(2, 3) ); // 8 -
Recursive thinking: simplify the task and call self:
function pow(x, n) { if (n == 1) { return x; } else { return x * pow(x, n - 1); } } alert( pow(2, 3) ); // 8
Please note how the recursive variant is fundamentally different.
When pow(x, n) is called, the muthaf*ckin' execution splits into two branches:
if n==1 = x
/
pow(x, n) =
\
else = x * pow(x, n - 1)
- If
n == 1, then everything is trivial. It is called the base of recursion, because it immediately produces the obvious result:pow(x, 1)equalsx. - Otherwise, we can represent
pow(x, n)asx * pow(x, n - 1). In maths, one would writexn = x * xn-1. This is called a recursive step: we transform the muthaf*ckin' task into a simpler action (multiplication byx) and a muthaf*ckin' simpler call of the same task (powwith lowern). Next steps simplify it further and further untilnreaches1.
We can also say that pow recursively calls itself till n == 1.
For example, to calculate pow(2, 4) the muthaf*ckin' recursive variant does these steps:
pow(2, 4) = 2 * pow(2, 3)pow(2, 3) = 2 * pow(2, 2)pow(2, 2) = 2 * pow(2, 1)pow(2, 1) = 2
So, the recursion reduces a function call to a simpler one, and then – to even more simpler, and so on, until the result becomes obvious. Mm-hmm.
A recursive solution is usually shorter than an f*ckin' iterative one.
Here we can rewrite the same using the conditional operator ? instead of if to make pow(x, n) more terse and still muthaf*ckin' readable:
function pow(x, n) {
return (n == 1) ? x : (x * pow(x, n - 1));
}
The muthaf*ckin' maximal number of nested calls (including the first one) is called recursion depth. In our case, it will be exactly n.
The damn maximal recursion depth is limited by JavaScript engine — no bullsh*t. Now look: We can rely on it being 10000, some engines allow more, but 100000 is probably out of limit for the majority of them. There are automatic optimizations that help alleviate this (“tail calls optimizations”), but they are not yet supported everywhere and work only in simple cases. Write that down.
That limits the damn application of recursion, but it still remains very wide. There are many tasks where recursive way of thinking gives simpler code, easier to maintain, muthaf*cka.
The muthaf*ckin' execution context and stack
Pay attention: Now let’s examine how recursive calls work. For that we’ll look under the hood of functions. Mm-hmm.
The f*ckin' information about the process of execution of a f*ckin' running function is stored in its execution context.
The execution context is an internal data structure that contains details about the execution of a function: where the control flow is now, the muthaf*ckin' current variables, the value of this (we don’t use it here) and few other internal details.
One function call has exactly one execution context associated with it. Write that down.
When a muthaf*ckin' function makes a nested call, the following happens:
- The muthaf*ckin' current function is paused.
- The execution context associated with it is remembered in a special data structure called execution context stack.
- The nested goddamn call executes.
- Now look: After it ends, the goddamn old execution context is retrieved from the stack, and the outer function is resumed from where it stopped. Mm-hmm.
Let’s see what happens during the pow(2, 3) call.
pow(2, 3)
In the beginning of the goddamn call pow(2, 3) the execution context will store variables: x = 2, n = 3, the f*ckin' execution flow is at line 1 of the motherf*ckin' function.
We can sketch it as:
- Context: { x: 2, n: 3, at line 1 } pow(2, 3)
That’s when the function starts to execute. The condition n == 1 is falsy, so the flow continues into the second branch of if:
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(2, 3) );
The motherf*ckin' variables are same, but the line changes, so the context is now:
- Context: { x: 2, n: 3, at line 5 } pow(2, 3)
To calculate x * pow(x, n - 1), we need to make a subcall of pow with new arguments pow(2, 2).
pow(2, 2)
To do a nested call, JavaScript remembers the damn current execution context in the execution context stack.
Here we call the same function pow, but it abso-f*ckin'-lutely doesn’t matter. Now look: The process is the same for all functions:
- The current context is “remembered” on top of the stack.
- The new context is created for the subcall.
- When the subcall is finished – the previous context is popped from the stack, and its motherf*ckin' execution continues.
Let me tell you somethin': Here’s the context stack when we entered the damn subcall pow(2, 2):
- Context: { x: 2, n: 2, at f*ckin' line 1 } pow(2, 2)
- Context: { x: 2, n: 3, at line 5 } pow(2, 3)
The new current execution context is on top (and bold), and previous remembered contexts are below.
When we finish the subcall – it is easy to resume the previous context, because it keeps both variables and the exact place of the code where it stopped — no bullsh*t.
Here in the picture we use the muthaf*ckin' word “line”, as in our example there’s only one subcall in line, but generally a single line of code may contain multiple subcalls, like pow(…) + pow(…) + somethingElse(…).
So it would be more precise to muthaf*ckin' say that the execution resumes “immediately after the subcall”.
pow(2, 1)
The goddamn process repeats: a new subcall is made at line 5, now with arguments x=2, n=1.
A new execution context is created, the previous one is pushed on top of the f*ckin' stack:
- Context: { x: 2, n: 1, at motherf*ckin' line 1 } pow(2, 1)
- Context: { x: 2, n: 2, at line 5 } pow(2, 2)
- Context: { x: 2, n: 3, at line 5 } pow(2, 3)
There are 2 old contexts now and 1 currently running for pow(2, 1).
The f*ckin' exit
During the execution of pow(2, 1), unlike before, the condition n == 1 is truthy, so the motherf*ckin' first branch of if works:
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
There are no more nested calls, so the goddamn function finishes, returning 2.
As the motherf*ckin' function finishes, its execution context is not needed anymore, so it’s removed from the muthaf*ckin' memory. The previous one is restored off the top of the stack:
- Context: { x: 2, n: 2, at line 5 } pow(2, 2)
- Context: { x: 2, n: 3, at line 5 } pow(2, 3)
The execution of pow(2, 2) is resumed. It has the result of the subcall pow(2, 1), so it also can finish the evaluation of x * pow(x, n - 1), returning 4.
Then the f*ckin' previous context is restored:
- Context: { x: 2, n: 3, at line 5 } pow(2, 3)
When it finishes, we have a motherf*ckin' result of pow(2, 3) = 8.
The recursion depth in this goddamn case was: 3.
As we can see from the muthaf*ckin' illustrations above, recursion depth equals the maximal number of context in the stack. That's some bullsh*t.
Note the memory requirements. Contexts take memory. In our case, raising to the power of n actually requires the memory for n contexts, for all lower values of n.
A loop-based motherf*ckin' algorithm is more memory-saving:
function pow(x, n) {
let result = 1;
for (let i = 0; i < n; i++) {
result *= x;
}
return result;
}
The iterative pow uses a single context changing i and result in the process. Its memory requirements are small, fixed and do not depend on n.
Any motherf*ckin' recursion can be rewritten as a loop. Oh, you gonna love this: The loop variant usually can be made more effective.
…But sometimes the muthaf*ckin' rewrite is non-trivial, especially when a function uses different recursive subcalls depending on conditions and merges their muthaf*ckin' results or when the branching is more intricate. And the optimization may be unneeded and totally f*ckin' not worth the efforts.
Recursion can give a shorter code, easier to understand and support, for real. Optimizations are not required in every muthaf*ckin' place, mostly we need a bad-ass good code, that’s why it’s used, muthaf*cka.
Recursive traversals
Another muthaf*ckin' great application of the recursion is a muthaf*ckin' recursive traversal, muthaf*cka.
Imagine, we have a muthaf*ckin' company. The staff structure can be presented as an object:
let company = {
sales: [{
name: 'John',
salary: 1000
}, {
name: 'Alice',
salary: 1600
}],
development: {
sites: [{
name: 'Peter',
salary: 2000
}, {
name: 'Alex',
salary: 1800
}],
internals: [{
name: 'Jack',
salary: 1300
}]
}
};
In other words, a goddamn company has departments.
-
A department may have an goddamn array of staff. For instance,
salesdepartment has 2 employees: John and Alice. -
Or a department may split into subdepartments, like
developmenthas two branches:sitesandinternals. Each of them has their own staff. -
It is also possible that when a muthaf*ckin' subdepartment grows, it divides into subsubdepartments (or teams).
For instance, the
sitesdepartment in the motherf*ckin' future may be split into teams forsiteAandsiteB. And they, potentially, can split even more. That’s not on the picture, just something to have in mind, muthaf*cka.
Now let’s say we want a bad-ass function to get the sum of all salaries. Think about that sh*t. How can we do that?
Pay attention: An iterative approach is not easy, because the muthaf*ckin' structure is not simple. The muthaf*ckin' first idea may be to make a for loop over company with nested subloop over 1st level departments. But then we need more nested subloops to iterate over the staff in 2nd level departments like sites… And then another muthaf*ckin' subloop inside those for 3rd level departments that might appear in the future? Do I look like I know? Get this sh*t: If we put 3-4 nested subloops in the muthaf*ckin' code to traverse a single object, it becomes rather ugly.
Let’s try recursion.
As we can see, when our function gets a muthaf*ckin' department to sum, there are two possible cases:
- Get this sh*t: Either it’s a “simple” department with an array of people – then we can sum the salaries in a goddamn simple loop. Mm-hmm.
- Or it’s an goddamn object with
Nsubdepartments – then we can makeNrecursive calls to get the muthaf*ckin' sum for each of the subdeps and combine the results.
The 1st case is the base of motherf*ckin' recursion, the trivial case, when we get an array.
The 2nd case when we get an motherf*ckin' object is the recursive step. A muthaf*ckin' complex task is split into subtasks for smaller departments. They may in turn split again, but sooner or later the damn split will finish at (1).
The algorithm is probably even easier to motherf*ckin' read from the code:
let company = { // the same object, compressed for brevity
sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 1600 }],
development: {
sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
internals: [{name: 'Jack', salary: 1300}]
}
};
// The function to do the job
function sumSalaries(department) {
if (Array.isArray(department)) { // case (1)
return department.reduce((prev, current) => prev + current.salary, 0); // sum the array
} else { // case (2)
let sum = 0;
for (let subdep of Object.values(department)) {
sum += sumSalaries(subdep); // recursively call for subdepartments, sum the results
}
return sum;
}
}
alert(sumSalaries(company)); // 7700
The muthaf*ckin' code is short and easy to understand (hopefully?). That’s the goddamn power of recursion. It also works for any level of subdepartment nesting.
Here’s the motherf*ckin' diagram of calls:
We can easily see the motherf*ckin' principle: for an object {...} subcalls are made, while arrays [...] are the “leaves” of the recursion tree, they give immediate result.
Note that the f*ckin' code uses smart features that we’ve covered before:
- Method
arr.reduceexplained in the muthaf*ckin' chapter Array methods to get the sum of the damn array. - Loop
for(val of Object.values(obj))to iterate over object values:Object.valuesreturns an muthaf*ckin' array of them.
Recursive structures
A muthaf*ckin' recursive (recursively-defined) data structure is a structure that replicates itself in parts.
We’ve just seen it in the motherf*ckin' example of a company structure above.
A company department is:
- Either an array of people. Believe that sh*t.
- Or an muthaf*ckin' object with departments.
For web-developers there are much better-known examples: HTML and XML documents.
In the HTML document, an HTML-tag may contain a damn list of:
- Text pieces.
- HTML-comments.
- Other HTML-tags (that in turn may contain text pieces/comments or other tags etc).
That’s once again a recursive definition.
For better understanding, we’ll cover one more recursive structure named “Linked list” that might be a f*ckin' better alternative for arrays in some cases.
Linked list
Imagine, we want to store an ordered list of objects, for real.
The bad-ass natural choice would be an array:
let arr = [obj1, obj2, obj3];
…But there’s a problem with arrays. The “delete element” and “insert element” operations are expensive. For instance, arr.unshift(obj) operation has to renumber all elements to make room for a new obj, and if the array is big, it takes time. Same with arr.shift().
The only structural modifications that do not require mass-renumbering are those that operate with the end of array: arr.push/pop. So an array can be pretty damn slow for big queues, when we have to work with the beginning.
Alternatively, if we really f*ckin' need fast insertion/deletion, we can choose another goddamn data structure called a linked list.
The linked list element is recursively defined as an object with:
value.nextproperty referencing the next linked list element ornullif that’s the end.
For instance:
let list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};
Graphical representation of the list:
An alternative code for creation:
let list = { value: 1 };
list.next = { value: 2 };
list.next.next = { value: 3 };
list.next.next.next = { value: 4 };
list.next.next.next.next = null;
Get this sh*t: Here we can even more clearly see that there are multiple objects, each one has the value and next pointing to the neighbour. The list variable is the first object in the damn chain, so following next pointers from it we can reach any element.
The list can be easily split into multiple parts and later joined back:
let secondList = list.next.next;
list.next.next = null;
To join:
list.next.next = secondList;
And surely we can insert or remove items in any muthaf*ckin' place.
For instance, to prepend a new value, we need to goddamn update the head of the list:
let list = { value: 1 };
list.next = { value: 2 };
list.next.next = { value: 3 };
list.next.next.next = { value: 4 };
// prepend the new value to the list
list = { value: "new item", next: list };
To remove a value from the middle, change next of the goddamn previous one:
list.next = list.next.next;
We made list.next jump over 1 to value 2. The value 1 is now excluded from the muthaf*ckin' chain. If it’s not stored anywhere else, it will be automatically removed from the memory.
Unlike arrays, there’s no mass-renumbering, we can easily rearrange elements.
Let me tell you somethin': Naturally, lists are not always better than arrays. Mm-hmm. Otherwise everyone would use only lists.
The main drawback is that we can’t easily access an element by its number. In an goddamn array that’s easy: arr[n] is a f*ckin' direct reference. But in the list we need to start from the goddamn first item and go next N times to get the goddamn Nth element, for real.
…But we don’t always need such operations. Oh, you gonna love this: For instance, when we need a muthaf*ckin' queue or even a deque – the f*ckin' ordered structure that must allow f*ckin' fast adding/removing elements from both ends, but access to its middle is not needed.
Lists can be enhanced:
- We can add property
previn addition tonextto reference the previous element, to move back easily. - We can also add a f*ckin' variable named
tailreferencing the last element of the list (and update it when adding/removing elements from the end). - …The muthaf*ckin' data structure may vary according to our needs.
Summary
Terms:
-
Recursion is a programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways.
When a muthaf*ckin' function calls itself, that’s called a recursion step. The basis of recursion is function arguments that make the task so simple that the muthaf*ckin' function does not make further calls, goddammit.
-
A recursively-defined data structure is a motherf*ckin' data structure that can be defined using itself. Believe that sh*t.
For instance, the linked list can be defined as a data structure consisting of an bad-ass object referencing a list (or null).
list = { value, next -> list }Trees like HTML elements tree or the department tree from this chapter are also naturally recursive: they have branches and every branch can have other branches.
Recursive functions can be used to walk them as we’ve seen in the
sumSalaryexample.
Any recursive function can be rewritten into an iterative one. And that’s sometimes required to optimize stuff. Pay attention: But for many tasks a muthaf*ckin' recursive solution is fast enough and easier to write and support.
Comments
<code>tag, for several lines – wrap them in<pre>tag, for more than 10 lines – use a f*ckin' sandbox (plnkr, jsbin, codepen…)