[{"data":1,"prerenderedAt":123},["ShallowReactive",2],{"course-en-recursion":3},{"lesson":4,"number":114,"prev":115,"next":119},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":84,"exercises":95},"recursion",{"ru":7,"en":8},"","Recursion",{"ru":7,"en":10},"Base and recursive cases in JavaScript, stack overflow in deep recursion, why not to rely on tail calls, and how a trampoline keeps the stack from growing.",{"ru":7,"en":12},"Learn to write recursive functions with a base case and a recursive case, and understand why deep recursion in JS overflows the stack and how a trampoline avoids it.",[14,17,19,27,29,33,35,38,40,42,45,47,49,51,57,60,62,64,78,81],{"type":15,"ru":7,"en":16},"text","Recursion is the ability of a function to call itself.",{"type":15,"ru":7,"en":18},"Recursion must meet two basic requirements in order to work correctly.",{"type":20,"ordered":21,"items":22},"list",true,[23,25],{"ru":7,"en":24},"The base case. This is the logic at which the recursion must stop — the base condition that stops the function from calling itself.",{"ru":7,"en":26},"The recursive case. This is the logic in which the function calls itself, usually with small changes to the arguments.",{"type":15,"ru":7,"en":28},"Recursion is frequently used in functional programming.",{"type":30,"code":31},"code",{"ru":7,"en":32},"\u002F\u002F our goal is to get the average age of the users\n\n\u002F\u002F ================================\n\u002F\u002F declarative style without recursion\n\n\u002F\u002F list of users\nconst fetchAllUsers = () => new Promise(resolve => resolve([\n  { name: 'John', status: 'online', age: 28 },\n  { name: 'Angel', status: 'online', age: 35 },\n  { name: 'Michel', status: 'offline', age: 18 },\n  { name: 'Anna', status: 'offline', age: 20 },\n]))\n\n\u002F\u002F pipe from the \"Function composition\" lesson: passes each function's result to the next one\nconst pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)\n\n\u002F\u002F getAgeAverage :: [a] -> Number\nconst getAgeAverage = (users) => pipe (\n  (users) => [\n    users.reduce ((init, { age }) => init + age, 0),\n    users.length\n    ], \u002F\u002F get the total age and the number of users\n  ([allAges, quantity]) => Math.round (allAges \u002F quantity), \u002F\u002F compute the average age\n  console.log \u002F\u002F log the result\n) (users)\n\nfetchAllUsers().then(getAgeAverage)\n\u002F\u002F ================================\n\n\u002F\u002F Recursive example\n\u002F\u002F ================================\n\u002F\u002F this recursive function is written with a tail call:\n\u002F\u002F the sum accumulates in the arguments, and in the base case the function\n\u002F\u002F returns the result right away, with no computation on the way back\n\u002F\u002F but we'll talk about that later\n\n\u002F\u002F now let's do the same thing with recursion\n\u002F\u002F recurAgeAverage :: ([a], Number, Number) -> Number\nconst recurAgeAverage = (\n    users, \u002F\u002F array of user data\n    sumAges = 0, \u002F\u002F sum of the users' ages\n    quantityUsers = users.length \u002F\u002F initial number of users\n  ) => {\n\n  \u002F\u002F base case, the exit condition:\n  \u002F\u002F the array is already empty\n  if (!users.length) {\n    \u002F\u002F divide the sum of all ages by the number of users\n    \u002F\u002F to get the average age of the users\n    return sumAges \u002F quantityUsers\n  }\n\n  \u002F\u002F recursive case: the function calls itself\n  \u002F\u002F while the array still has elements\n  return recurAgeAverage (\n      users.slice(1), \u002F\u002F the array without its first element\n      sumAges = sumAges + users[0]?.age, \u002F\u002F add up each user's age\n      quantityUsers \u002F\u002F pass along the previously saved number of users\n    )\n}\n\u002F\u002F ================================\n\n\u002F\u002F Let's rewrite our function as a one-liner and call it\nconst recurAgeAverageF = (users, sumAges = 0, quantityUsers = users.length) =>\n                          !users.length\n                              ? sumAges \u002F quantityUsers\n                              : recurAgeAverageF (\n                                  users.slice(1),\n                                  sumAges = sumAges + users[0]?.age,\n                                  quantityUsers\n                                )\n\n\u002F\u002F the semicolon before the parenthesis is required: without it JS joins\n\u002F\u002F this parenthesis to the expression above and tries to call its result\n;( async () => {\n  const users = await fetchAllUsers () \u002F\u002F get the list of users\n  const averageAge = recurAgeAverageF (users) \u002F\u002F get the average age recursively\n  console.log (averageAge) \u002F\u002F log the result: 25.25\n}\n)()",{"type":15,"ru":7,"en":34},"The example above with recursion may not be simple for some. So we will write a simpler example and visualize the calls. The main thing is, don't worry if something isn't clear right away.",{"type":30,"code":36},{"ru":7,"en":37},"\u002F\u002F Our goal is to get the total rating of the users,\n\u002F\u002F that is, the sum of their ratings\n\nconst users = [\n  { name: 'John', rating: 4.5 },\n  { name: 'Angel', rating: 4 },\n  { name: 'Michel', rating: 3 },\n  { name: 'Anna', rating: 5 },\n]\n\n\u002F\u002F sumRating :: [a] -> Number\nconst sumRating = (users) => {\n  \u002F\u002F base case, the exit condition: the array is empty\n  if (!users.length) {\n    return 0\n  }\n\n  \u002F\u002F recursive case:\n  \u002F\u002F the rating of the first element is added\n  \u002F\u002F to the call of the same function on the array without that element\n  return users[0].rating + sumRating (users.slice(1))\n}\n\n\u002F\u002F let's shorten the syntax\nconst rateSum = (users) =>\n                      !users.length\n                        ? 0\n                        :  users[0] + rateSum (users.slice(1))\n\n\u002F\u002F let's visualize the calls\n\u002F\u002F to keep it simple, use an array of numbers instead of the rating key\nrateSum ([4.5, 4, 3, 5]) \u002F\u002F returns 4.5 + rateSum ([4, 3, 5])\nrateSum ([4, 3, 5]) \u002F\u002F returns 4 + rateSum ([3, 5])\nrateSum ([3, 5]) \u002F\u002F returns 3 + rateSum ([5])\nrateSum ([5]) \u002F\u002F returns 5 + rateSum ([])\nrateSum ([]) \u002F\u002F returns 0: we reached the base case\n\n\u002F\u002F and here comes the key part: the calls on the stack return one by one\nrateSum ([5]) \u002F\u002F returns 5 + 0\nrateSum ([3, 5]) \u002F\u002F returns 3 + 5\nrateSum ([4, 3, 5]) \u002F\u002F returns 4 + 8\nrateSum ([4.5, 4, 3, 5]) \u002F\u002F returns 4.5 + 12\n\u002F\u002F final result: 16.5",{"type":15,"ru":7,"en":39},"The \"rateSum\" function in the example above has one significant drawback: each call waits for the result of the next one so it can add its own number to it. So the depth of the call stack grows with the length of the array. Let's see what tail recursion changes here.",{"type":15,"ru":7,"en":41},"Why do we need this? Until a call finishes, its frame (arguments, local variables and the place to return the result to) stays on the call stack. The stack size is limited, so on a large array synchronous recursion fails with a stack overflow error (in Chrome and Node.js it is RangeError: Maximum call stack size exceeded).",{"type":30,"code":43},{"ru":7,"en":44},"\u002F\u002F === Tail recursion optimization ====\n\u002F\u002F Let's rewrite the function so that the recursive call becomes a tail call\nconst rateSum = (users, result = 0) => {\n  \u002F\u002F base case, the exit condition: the array is empty\n  \u002F\u002F return the second argument, where we accumulate\n  \u002F\u002F the results of all the calls\n  if (!users.length) {\n    return result\n  }\n\n  \u002F\u002F recursive case, while the array has elements:\n  \u002F\u002F on each call we add to the result in the second argument\n  \u002F\u002F and keep calling, and in the base case we return the result\n  \u002F\u002F the call is in tail position: after it the function has nothing left to do\n  return rateSum (users.slice(1), result = result + users[0])\n}\n\n\u002F\u002F let's rewrite it all as a one-liner\nconst sum = (users, result = 0) => !users.length\n                                ? result\n                                : sum (users.slice(1), result = result + users[0])\n\n\u002F\u002F let's visualize the calls\n\u002F\u002F to keep it simple, use an array of numbers instead of the rating key\nsum ([4.5, 4, 3, 5], 0) \u002F\u002F returns sum ([4, 3, 5], 0 + 4.5)\nsum ([4, 3, 5], 4.5) \u002F\u002F returns sum ([3, 5], 4.5 + 4)\nsum ([3, 5], 8.5) \u002F\u002F returns sum ([5], 8.5 + 3)\nsum ([5], 11.5) \u002F\u002F returns sum ([], 11.5 + 5)\nsum ([], 16.5) \u002F\u002F returns result 16.5\n\u002F\u002F the calls stop here: the result is already in the accumulator,\n\u002F\u002F and there is nothing left to compute on the way back\n\u002F\u002F there are as many calls as in rateSum without the accumulator: five\n\u002F\u002F with proper tail calls the engine keeps no frames of waiting calls,\n\u002F\u002F and the stack depth does not grow; but they only work in strict mode,\n\u002F\u002F and among browsers only Safari has them: V8 and SpiderMonkey don't\n\u002F\u002F this example is written without 'use strict', so its stack grows everywhere,\n\u002F\u002F even in Safari, just as it does without a tail call",{"type":15,"ru":7,"en":46},"A tail call does not reduce the number of calls. It lets the engine drop the caller's stack frame: ES2015 requires this in strict mode (proper tail calls), and then the stack depth does not grow. Among browser engines, only JavaScriptCore (Safari) implements it; V8 (Chrome, Node.js) had it behind a flag and removed it, and SpiderMonkey (Firefox) does not have it. That is why deep recursion in JS needs a trampoline. In production code, don't rely on tail recursion unless you know exactly how many calls there will be.",{"type":15,"ru":7,"en":48},"Further on in the recursion section we will use techniques that let you safely use recursion in production code without counting the number of calls.",{"type":15,"ru":7,"en":50},"So how do we free up the call stack without overflowing it in production code?",{"type":20,"ordered":21,"items":52},[53,55],{"ru":7,"en":54},"Make the code asynchronous, avoid blocking the thread, and free up the stack",{"ru":7,"en":56},"Use a trampoline. A thunk is a function with no arguments that defers a computation; a trampoline is a loop that keeps calling thunks while the result is a function. The recursive calls turn into a loop, so the stack does not grow.",{"type":30,"code":58},{"ru":7,"en":59},"\u002F\u002F === 1. Asynchronous recursive call ====\n\n\u002F\u002F note that the recursive case is wrapped in a timer\n\u002F\u002F sumD :: ([Number], Number, (Number -> *)) -> Undefined\nconst sumD = (users, result = 0, callback) => {\n\n  \u002F\u002F base case, the exit condition:\n  \u002F\u002F once the array is empty, pass the result to the callback\n  if (!users.length) {\n    callback (result)\n    return\n  }\n\n  \u002F\u002F the recursive case is called asynchronously,\n  \u002F\u002F through a timer, so that the stack does not overflow\n  setTimeout (\n    () => sumD (users.slice(1), result = result + users[0], callback),\n    0\n  )\n}\n\n\u002F\u002F let's shorten it\nconst sum = (users, result = 0, callback) =>\n  !users.length\n    ? callback (result)\n    : setTimeout (\n        () => sum (users.slice(1), result = result + users[0], callback),\n        0\n      )\n\n\u002F\u002F let's try calling it\nsum ([4.5, 4, 3, 5], 0, (total) => console.log(total)) \u002F\u002F 16.5\n\n\u002F\u002F let's visualize the calls\nsum ([4.5, 4, 3, 5], 0, (total) => console.log(total)) \u002F\u002F schedules sum ([4, 3, 5], 0 + 4.5, callback) via a timer\n\u002F\u002F the call stack is free: microtasks (promises) and other macrotasks run between the steps\n\u002F\u002F the thread is not blocked\n\u002F\u002F the stack does not overflow\nsum ([4, 3, 5], 4.5, (total) => console.log(total)) \u002F\u002F schedules sum ([3, 5], 4.5 + 4, callback) via a timer\n\u002F\u002F the call stack is free: microtasks (promises) and other macrotasks run between the steps\n\u002F\u002F the thread is not blocked\n\u002F\u002F the stack does not overflow\nsum ([3, 5], 8.5, (total) => console.log(total)) \u002F\u002F schedules sum ([5], 8.5 + 3, callback) via a timer\n\u002F\u002F the call stack is free: microtasks (promises) and other macrotasks run between the steps\n\u002F\u002F the thread is not blocked\n\u002F\u002F the stack does not overflow\nsum ([5], 11.5, (total) => console.log(total)) \u002F\u002F schedules sum ([], 11.5 + 5, callback) via a timer\n\u002F\u002F the call stack is free: microtasks (promises) and other macrotasks run between the steps\n\u002F\u002F the thread is not blocked\n\u002F\u002F the stack does not overflow\nsum ([], 16.5, (total) => console.log(total)) \u002F\u002F calls callback with result\n\n\u002F\u002F Downsides of this approach\n\u002F\u002F Execution speed (performance) is low\n\u002F\u002F If you need long-running synchronous computations,\n\u002F\u002F it's better to move them to a web worker so they don't block the main thread;\n\u002F\u002F on a multi-core CPU the computation will also run in parallel",{"type":15,"ru":7,"en":61},"Let's examine the logic of using a trampoline to avoid stack overflow. The trampoline works synchronously, unlike a call through a timer.",{"type":15,"ru":7,"en":63},"Let's look at the main principles of the trampoline.",{"type":20,"ordered":21,"items":65},[66,68,70,72,74,76],{"ru":7,"en":67},"A trampoline is a wrapper function that gives our main function special behavior.",{"ru":7,"en":69},"The trampoline function returns another function that accepts arguments.",{"ru":7,"en":71},"Inside, it calls the main function once with these arguments.",{"ru":7,"en":73},"While the returned value is a function, the trampoline calls it in a loop. As soon as the result is not a function, the loop stops and the trampoline returns the result.",{"ru":7,"en":75},"In the base case the main function must return a result.",{"ru":7,"en":77},"In the recursive case the main function must return a function with no arguments (a thunk) that performs the next step.",{"type":30,"code":79},{"ru":7,"en":80},"\u002F\u002F === Recursion via a trampoline ====\n\n\u002F\u002F note: the first call takes the function,\n\u002F\u002F and the second takes its arguments, which starts the computation\n\u002F\u002F trampoline :: ((...args -> *) -> (...args -> *))\nconst trampoline = (fn) => (...args) => {\n  \u002F\u002F run the function with the given arguments\n  let result = fn(...args)\n\n  \u002F\u002F keep looping while the function\n  \u002F\u002F returns another function\n  while (typeof result == 'function') {\n    \u002F\u002F store the result of the call in the variable\n    \u002F\u002F and check what it returned\n    \u002F\u002F result() *** remember this mark, we'll show later what this function is\n    result = result()\n  }\n\n  \u002F\u002F as soon as the result of the call\n  \u002F\u002F is not a function, return it\n  return result\n}\n\n\u002F\u002F let's shorten the notation\n\u002F\u002F sumD :: ([Number], Number) -> (Number | (() -> *))\nconst sumD = (users, result = 0) => {\n\n  \u002F\u002F if the array is empty, return the result\n  if (!users.length) {\n    return result\n  }\n\n  \u002F\u002F note: here we must return a function with no arguments (a thunk)\n  \u002F\u002F mark *** this is the function the trampoline calls inside the loop\n  return () => sumD (users.slice(1), result = result + users[0])\n}\n\n\u002F\u002F let's rewrite the function as a one-liner\n\u002F\u002F sum :: ([Number], Number) -> (Number | (() -> *))\nconst sum = (users, result = 0) =>\n      !users.length\n       ? result\n       : () => sum (users.slice(1), result = result + users[0])\n\n\u002F\u002F let's test the code\n\n\u002F\u002F pass our function through the trampoline\nconst sumTrampoline = trampoline (sum)\n\n\u002F\u002F now the functions will actually run in a loop\nconsole.log (sumTrampoline ([4.5, 4, 3, 5], 0)) \u002F\u002F 16.5",{"type":30,"pseudo":21,"code":82},{"ru":7,"en":83},"\u002F\u002F now let's visualize the calls\n\u002F\u002F the logic inside the trampoline for sumTrampoline ([4.5, 4, 3, 5], 0)\n\n\u002F\u002F  === first call, before the loop =====\nlet result = sum ([4.5, 4, 3, 5], 0)\n\u002F\u002F puts () => sum ([4, 3, 5], 0 + 4.5) into result\n\u002F\u002F =======================\n\n\u002F\u002F  === while loop: each iteration calls one function =====\nresult = result () \u002F\u002F calls sum ([4, 3, 5], 4.5)\n\u002F\u002F puts () => sum ([3, 5], 4.5 + 4) into result\n\nresult = result () \u002F\u002F calls sum ([3, 5], 8.5)\n\u002F\u002F puts () => sum ([5], 8.5 + 3) into result\n\nresult = result () \u002F\u002F calls sum ([5], 11.5)\n\u002F\u002F puts () => sum ([], 11.5 + 5) into result\n\nresult = result () \u002F\u002F calls sum ([], 16.5)\n\u002F\u002F puts 16.5 into result: it is no longer a function, so the loop ends\n\u002F\u002F =======================\n\n\u002F\u002F  === leaving the trampoline =====\nreturn result \u002F\u002F 16.5\n\u002F\u002F =======================\n\n\n\u002F\u002F visualized as a diagram\n\u002F\u002F it's like a linked list of functions that isn't built in advance\n\u002F\u002F but grows as we go: the next element appears\n\u002F\u002F when the previous one is called\n[\n  sum ([4.5, 4, 3, 5], 0), \u002F\u002F first call: let result = fn(...args)\n  () => sum ([4, 3, 5], 4.5), \u002F\u002F result = result() inside the loop\n  () => sum ([3, 5], 8.5), \u002F\u002F result = result() inside the loop\n  () => sum ([5], 11.5), \u002F\u002F result = result() inside the loop\n  () => sum ([], 16.5), \u002F\u002F result = result() inside the loop\n  16.5 \u002F\u002F the loop ends: return result\n]",[85,87,89,91,93],{"ru":7,"en":86},"Recursion needs two cases: the base case stops the calls, and the recursive case calls the function again, usually with small changes to the arguments.",{"ru":7,"en":88},"Until a call finishes, its frame stays on the call stack. The stack size is limited, so on a large array synchronous recursion fails with a stack overflow.",{"ru":7,"en":90},"A tail call does not reduce the number of calls. ES2015 requires the engine to drop the caller's stack frame only in strict mode (proper tail calls), and among browser engines only JavaScriptCore (Safari) implements it. So production code should not rely on tail recursion unless you know exactly how many calls there will be.",{"ru":7,"en":92},"You can free the stack by running the recursive step asynchronously through a timer: the thread is not blocked, but such code is slow.",{"ru":7,"en":94},"A trampoline works synchronously: in the recursive case the function returns a thunk, a function with no arguments holding the next step, and the trampoline calls these functions in a loop while the result is a function. The stack does not grow.",[96,105],{"task":97,"starter":99,"solution":101,"expected":103},{"ru":7,"en":98},"Write a recursive function flatten that turns an array with nested arrays of any depth into a flat array, without using the built-in flat method. Define the base case first, then the recursive case: what to do when the first element is itself an array, and what to do when it is not.",{"ru":7,"en":100},"\u002F\u002F flatten :: [*] -> [*]\nconst flatten = (arr) => {\n  \u002F\u002F your code\n}\n\nconsole.log(flatten([1, [2, [3, [4]], 5], [[6]]]))\nconsole.log(flatten([]))",{"ru":7,"en":102},"\u002F\u002F flatten :: [*] -> [*]\nconst flatten = (arr) => {\n  \u002F\u002F base case: an empty array has nothing to flatten\n  if (!arr.length) {\n    return []\n  }\n\n  const [head, ...tail] = arr\n\n  \u002F\u002F recursive case: flatten a nested array with the same function,\n  \u002F\u002F keep a plain value as is, and go on with the tail\n  return Array.isArray(head)\n    ? [...flatten(head), ...flatten(tail)]\n    : [head, ...flatten(tail)]\n}\n\nconsole.log(flatten([1, [2, [3, [4]], 5], [[6]]]))\nconsole.log(flatten([]))",{"ru":7,"en":104},"[\n  1,\n  2,\n  3,\n  4,\n  5,\n  6\n]\n[]",{"task":106,"starter":108,"solution":110,"expected":112},{"ru":7,"en":107},"The sumTo function adds up the numbers from 1 to n with plain recursion, and sumTo(100000) fails in Chrome and Node.js with RangeError: Maximum call stack size exceeded. Rewrite it for the trampoline from the lesson: keep the sum in an accumulator, and in the recursive case return a thunk with the next step. Check the result for 10 and for 100,000.",{"ru":7,"en":109},"\u002F\u002F the trampoline from the lesson\n\u002F\u002F trampoline :: ((...args -> *) -> (...args -> *))\nconst trampoline = (fn) => (...args) => {\n  let result = fn(...args)\n\n  while (typeof result === 'function') {\n    result = result()\n  }\n\n  return result\n}\n\n\u002F\u002F plain recursion: each call waits for the result of the next one\n\u002F\u002F sumTo :: Number -> Number\nconst sumTo = (n) => n === 0 ? 0 : n + sumTo(n - 1)\n\n\u002F\u002F sumToStep returns either the sum or a thunk with the next step\n\u002F\u002F sumToStep :: (Number, Number) -> (Number | (() -> *))\nconst sumToStep = (n, acc = 0) => {\n  \u002F\u002F your code\n}\n\n\u002F\u002F sumToSafe :: Number -> Number\nconst sumToSafe = trampoline(sumToStep)\n\nconsole.log(sumToSafe(10))\nconsole.log(sumToSafe(100000))",{"ru":7,"en":111},"\u002F\u002F the trampoline from the lesson\n\u002F\u002F trampoline :: ((...args -> *) -> (...args -> *))\nconst trampoline = (fn) => (...args) => {\n  let result = fn(...args)\n\n  while (typeof result === 'function') {\n    result = result()\n  }\n\n  return result\n}\n\n\u002F\u002F sumToStep :: (Number, Number) -> (Number | (() -> *))\nconst sumToStep = (n, acc = 0) =>\n  n === 0\n    ? acc \u002F\u002F base case: the sum is already in the accumulator\n    : () => sumToStep(n - 1, acc + n) \u002F\u002F recursive case: a thunk with the next step\n\n\u002F\u002F sumToSafe :: Number -> Number\nconst sumToSafe = trampoline(sumToStep)\n\nconsole.log(sumToSafe(10))\nconsole.log(sumToSafe(100000))",{"ru":7,"en":113},"55\n5000050000",13,{"slug":116,"title":117},"currying-and-asynchrony",{"ru":7,"en":118},"Currying and asynchrony (evolution)",{"slug":120,"title":121},"function-map-filter-reduce",{"ru":7,"en":122},"The map, filter, and reduce functions",1792684724640]