[{"data":1,"prerenderedAt":83},["ShallowReactive",2],{"course-en-composition":3},{"lesson":4,"number":74,"prev":75,"next":79},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":48,"exercises":55},"composition",{"ru":7,"en":8},"","Function composition",{"ru":7,"en":10},"Composing JavaScript functions with compose (right to left) and pipe (left to right), and writing pipe for any number of functions: loop, reduce, recursion.",{"ru":7,"en":12},"Understand what function composition is and learn to chain functions with compose and pipe, both for three functions and for any number of them.",[14,17,19,23,25,27,31,33,35,38,40,43,45],{"type":15,"ru":7,"en":16},"text","Function composition combines functions into a new function that calls them in sequence: the result of one function is passed to the next.",{"type":15,"ru":7,"en":18},"Function composition is one of the fundamental concepts on which category theory is based.",{"type":20,"code":21},"code",{"ru":7,"en":22},"\u002F\u002F === composing 3 functions ===\n\u002F\u002F compose :: ((c -> z), (b -> c), (a -> b)) -> a -> z\nconst compose = (f3, f2, f1) => (...args) => f3(f2(f1(...args)))\n\n\u002F\u002F using the function\n\u002F\u002F our goal\n\u002F\u002F 1. Get the users whose status is online\n\u002F\u002F 2. Take their names\n\u002F\u002F 3. Log the list of names\n\n\u002F\u002F fetchAllUsers :: () -> Promise [Object]\nconst fetchAllUsers = () => new Promise(resolve => resolve([\n  {\n    name: 'John',\n    status: 'online',\n    age: 25\n  },\n  {\n    name: 'Alex',\n    status: 'offline',\n    age: 18\n  },\n  {\n    name: 'Angel',\n    status: 'online',\n    age: 18\n  }\n]))\n\nfetchAllUsers() \u002F\u002F simulate a request\n  .then( \u002F\u002F wait for the response\n    compose( \u002F\u002F pass the result into the composed function\n        console.log, \u002F\u002F log the results\n        (usersActive) => usersActive.map(user => user.name), \u002F\u002F collect the names\n        (data) => data.filter(user => user.status === 'online'), \u002F\u002F filter by status\n      )\n    )\n\n\u002F\u002F the same composition, but within the Array type\n\u002F\u002F not quite the classic functional approach\nfetchAllUsers() \u002F\u002F simulate a request\n  .then( \u002F\u002F wait for the response\n      (data) => console.log(\n          data\n            .filter(user => user.status === 'online')\n            .map(user => user.name)\n        )\n    )\n\n\u002F\u002F ===============================",{"type":15,"ru":7,"en":24},"If you noticed in the example above, the functions executed from right to left — mathematically that's fine. But it is often more convenient for the reader to read code from left to right.",{"type":15,"ru":7,"en":26},"So we can rewrite the code above.",{"type":20,"noRun":28,"code":29},"previous-block",{"ru":7,"en":30},"\u002F\u002F === composing 3 functions in a human-readable order ===\n\u002F\u002F the order is now left to right\n\u002F\u002F pipe :: ((a -> b), (b -> c), (c -> z)) -> a -> z\nconst pipe = (f1, f2, f3) => (...args) => f3(f2(f1(...args)))\n\n\u002F\u002F Now the composition is easier to read, left to right\n\nfetchAllUsers() \u002F\u002F simulate a request\n  .then( \u002F\u002F wait for the response\n    pipe( \u002F\u002F pass the result into the composed function\n        (data) => data.filter(user => user.status === 'online'), \u002F\u002F filter by status\n        (usersActive) => usersActive.map(user => user.name), \u002F\u002F collect the names\n        console.log, \u002F\u002F log the results\n      )\n    )\n\n\u002F\u002F Note\n\n\u002F\u002F compose: order in which the functions run\n\u002F\u002F 3 \u003C- 2 \u003C- 1\n\n\u002F\u002F pipe\n\u002F\u002F 1 -> 2 -> 3\n\n\u002F\u002F ===============================",{"type":15,"ru":7,"en":32},"Now imagine a situation where the number of functions is more than 3.",{"type":15,"ru":7,"en":34},"In real projects, use compose or pipe from existing libraries. We will try to build pipe in several ways: imperatively, declaratively and recursively.",{"type":20,"code":36},{"ru":7,"en":37},"\u002F\u002F === composing an arbitrary number of functions ===\n\n\u002F\u002F === Imperative approach ===\n\u002F\u002F the order is now left to right\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (...args) => {\n\n  \u002F\u002F split the array of functions into head and tail\n  const [ head, ...tail ] = fns\n\n  \u002F\u002F variable holding the result of the first function\n  \u002F\u002F and then of each of the remaining ones\n  let result = head(...args)\n\n  \u002F\u002F call the remaining functions in a loop and overwrite\n  \u002F\u002F the variable with each result\n  for (const fn of tail) {\n    result = fn(result)\n  }\n\n  \u002F\u002F return the final result\n  return result\n}\n\n\u002F\u002F ===============================",{"type":15,"ru":7,"en":39},"Now let's implement it in a functional style, declaratively.",{"type":20,"code":41},{"ru":7,"en":42},"\u002F\u002F === composing an arbitrary number of functions ===\n\n\u002F\u002F === Declarative approach ===\n\u002F\u002F the order is now left to right\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (arg) => fns.reduce(\n    (init, fn) => fn(init), \u002F\u002F pass the accumulated value (arg on the first step) to the function\n    arg \u002F\u002F argument of the first call\n  )\n\n\u002F\u002F at first glance this function is fine,\n\u002F\u002F and from a functional point of view a single argument is better and more correct,\n\u002F\u002F but the first call may need 2 or more arguments\nconst pipeMultiArgs = (...fns) => (...args) => fns.reduce(\n    (init, fn, i) => i === 0 ? fn(...init) : fn(init) , \u002F\u002F first call or a later one?\n    args \u002F\u002F arguments of the first call\n)\n\n\u002F\u002F ===============================",{"type":15,"ru":7,"en":44},"We can also implement function composition recursively. The call pipe(...tail)(head(arg)) is in tail position, but that does not reduce the number of calls. With proper tail calls (ES2015, strict mode only) a tail call does not grow the stack, but among browser engines only JavaScriptCore (Safari) implements them: V8 (Chrome, Node.js) had them behind a flag and removed them, and SpiderMonkey (Firefox) does not have them. That is why deep recursion in JS needs a trampoline — more on it in the \"Recursion\" lesson. For a pipe of a few functions, stack depth is not a problem.",{"type":20,"code":46},{"ru":7,"en":47},"\u002F\u002F === composing an arbitrary number of functions ===\n\n\u002F\u002F === Recursive approach ===\n\u002F\u002F the order is now left to right\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (arg) => {\n\n  \u002F\u002F base case: only one function is left\n  if (fns.length === 1) {\n    return fns[0](arg)\n  }\n\n  \u002F\u002F split into head and tail:\n  \u002F\u002F the first function and the rest\n  const [head, ...tail] = fns\n\n  \u002F\u002F call pipe recursively for the tail,\n  \u002F\u002F and call the first function with the current argument\n  return pipe(...tail)(head(arg))\n}\n\n\u002F\u002F ===============================",[49,50,51,53],{"ru":7,"en":16},{"ru":7,"en":18},{"ru":7,"en":52},"compose calls the functions right to left, which is fine from a mathematical point of view, while pipe calls them left to right, which is often easier for the reader.",{"ru":7,"en":54},"pipe for any number of functions can be written imperatively (with a loop), declaratively (with reduce) or recursively; in real projects, use compose or pipe from existing libraries.",[56,65],{"task":57,"starter":59,"solution":61,"expected":63},{"ru":7,"en":58},"In the lesson, compose is written for exactly three functions, while pipe handles any number of them. Write compose for any number of functions: it should call them right to left. Check that compose(square, double, inc) and pipe(inc, double, square) give the same result, while compose(inc, double, square) gives a different one. Hint: arrays have a reduceRight method — the same as reduce, except that it walks the array from right to left.",{"ru":7,"en":60},"\u002F\u002F pipe: the declarative approach from the lesson\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)\n\n\u002F\u002F compose :: ((y -> z), ..., (b -> c), (a -> b)) -> a -> z\nconst compose = (...fns) => (arg) => {\n  \u002F\u002F your code\n}\n\n\u002F\u002F inc :: Number -> Number\nconst inc = (n) => n + 1\n\u002F\u002F double :: Number -> Number\nconst double = (n) => n * 2\n\u002F\u002F square :: Number -> Number\nconst square = (n) => n * n\n\nconsole.log(pipe(inc, double, square)(3))\nconsole.log(compose(square, double, inc)(3))\nconsole.log(compose(inc, double, square)(3))",{"ru":7,"en":62},"\u002F\u002F pipe: the declarative approach from the lesson\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)\n\n\u002F\u002F compose :: ((y -> z), ..., (b -> c), (a -> b)) -> a -> z\n\u002F\u002F reduceRight starts with the last function, so it is called first\nconst compose = (...fns) => (arg) => fns.reduceRight((init, fn) => fn(init), arg)\n\n\u002F\u002F inc :: Number -> Number\nconst inc = (n) => n + 1\n\u002F\u002F double :: Number -> Number\nconst double = (n) => n * 2\n\u002F\u002F square :: Number -> Number\nconst square = (n) => n * n\n\n\u002F\u002F inc, then double, then square: (3 + 1) * 2 = 8, 8 * 8 = 64\nconsole.log(pipe(inc, double, square)(3))\n\u002F\u002F the same order of calls, just written right to left\nconsole.log(compose(square, double, inc)(3))\n\u002F\u002F square, then double, then inc: 3 * 3 = 9, 9 * 2 = 18, 18 + 1 = 19\nconsole.log(compose(inc, double, square)(3))",{"ru":7,"en":64},"64\n64\n19",{"task":66,"starter":68,"solution":70,"expected":72},{"ru":7,"en":67},"Use pipe to build a slugify function that turns a lesson title into a URL anchor like the ones this course uses: \"Pure Functions\" → pure-functions. It trims the spaces at both ends, converts the string to lower case, splits it into words and joins them with hyphens. Make each step a separate function of one argument. Annotate the steps with Hindley–Milner notation and check that the result type of each step matches the argument type of the next one.",{"ru":7,"en":69},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)\n\n\u002F\u002F slugify :: String -> String\nconst slugify = pipe(\n  \u002F\u002F your code\n)\n\nconsole.log(slugify('Pure Functions'))\nconsole.log(slugify('  Partial Application  '))\nconsole.log(slugify('Imperative vs Declarative'))",{"ru":7,"en":71},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)\n\n\u002F\u002F trim :: String -> String\nconst trim = (str) => str.trim()\n\u002F\u002F toLower :: String -> String\nconst toLower = (str) => str.toLowerCase()\n\u002F\u002F words :: String -> [String]\nconst words = (str) => str.split(' ')\n\u002F\u002F joinWithDash :: [String] -> String\nconst joinWithDash = (list) => list.join('-')\n\n\u002F\u002F the result of each step is the argument of the next one:\n\u002F\u002F trim and toLower return a String, words takes a String and returns [String],\n\u002F\u002F joinWithDash takes [String] and returns a String\n\u002F\u002F slugify :: String -> String\nconst slugify = pipe(trim, toLower, words, joinWithDash)\n\nconsole.log(slugify('Pure Functions'))\nconsole.log(slugify('  Partial Application  '))\nconsole.log(slugify('Imperative vs Declarative'))",{"ru":7,"en":73},"pure-functions\npartial-application\nimperative-vs-declarative",8,{"slug":76,"title":77},"hindley-milner-type-notation",{"ru":7,"en":78},"Hindley–Milner type notation",{"slug":80,"title":81},"currying",{"ru":7,"en":82},"Currying",1792684724207]