[{"data":1,"prerenderedAt":93},["ShallowReactive",2],{"course-en-function-map-filter-reduce":3},{"lesson":4,"number":84,"prev":85,"next":89},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":54,"exercises":65},"function-map-filter-reduce",{"ru":7,"en":8},"","The map, filter, and reduce functions",{"ru":7,"en":10},"What map, filter and reduce do in JavaScript, how reduce emulates the other two, and how to write all three with a loop, declaratively and via a trampoline.",{"ru":7,"en":12},"Understand what map, filter and reduce do, and learn to implement them yourself: declaratively, imperatively and recursively with a trampoline.",[14,17,19,22,24,26,30,32,34,36,38,41,43,45,47,49,51],{"type":15,"ru":7,"en":16},"text","The most frequently used functions in functional programming and production code are map, filter, and reduce.",{"type":15,"ru":7,"en":18},"These functions provide powerful capabilities for working with data.",{"type":20,"ru":7,"en":21},"heading","map",{"type":15,"ru":7,"en":23},"The map function returns a new object of the same data type, passing each element through the function it receives as an argument when the type is iterable. If the type is not iterable, the contained data is simply passed through the function.",{"type":15,"ru":7,"en":25},"Let's implement the map function in several different ways.",{"type":27,"code":28},"code",{"ru":7,"en":29},"\u002F\u002F currying and taking the data as the last argument\n\u002F\u002F make these functions easy to use in composition\n\u002F\u002F in point-free style, without naming the data:\n\u002F\u002F pipe (mapD (f), filterD (g))\n\n\u002F\u002F ==== declarative implementation ====\n\u002F\u002F mapD :: (a -> b) -> [a] -> [b]\nconst mapD = (fn) => (arr) => arr.map(fn)\n\u002F\u002F ===================================\n\n\u002F\u002F ==== imperative implementation ====\n\u002F\u002F without the iteration index and context\n\u002F\u002F mapI :: (a -> b) -> [a] -> [b]\nconst mapI = (fn) => (arr) => {\n  \u002F\u002F the resulting array\n  \u002F\u002F that we will return\n  let result = []\n\n  for (const item of arr) {\n    \u002F\u002F pass each element through\n    \u002F\u002F the given function\n    result.push(fn(item)) \u002F\u002F or result = [ ...result, fn (item) ]\n  }\n\n  return result\n}\n \u002F\u002F ===================================\n\n\u002F\u002F ==== imperative implementation ====\n\u002F\u002F with the iteration index and context\n\u002F\u002F mapIq :: ((a, Number, [a]) -> b) -> [a] -> [b]\nconst mapIq = (fn) => (arr) => {\n  let result = []\n\n  for (let i = 0; i \u003C arr.length; i++ ) {\n    result.push(fn(arr[i], i, arr)) \u002F\u002F or result = [ ...result, fn (arr[i], i, arr) ]\n  }\n\n  return result\n}\n\u002F\u002F ===================================\n\n\u002F\u002F ==== recursive implementation ====\n\u002F\u002F through a trampoline, so the stack does not overflow\n\u002F\u002F I hope you have read the lesson on recursion\n\n\u002F\u002F trampoline :: ((...args -> *) -> (...args -> *))\n\u002F\u002F calls the function and, while the result is a function (a thunk),\n\u002F\u002F calls it again: the steps run in a loop, the stack does not grow\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 mapR returns either the finished array\n\u002F\u002F or a function with no arguments (a thunk) holding the next step\nconst mapR = (fn) => (arr, i = 0, acc = []) => {\n\n  \u002F\u002F base case\n  \u002F\u002F when the elements run out, return the accumulator\n  if (i === arr.length) {\n    return acc\n  }\n\n  \u002F\u002F recursive case\n  \u002F\u002F return a function for the trampoline\n  \u002F\u002F put the result of passing the element through the function into the accumulator\n  \u002F\u002F and move on to the next element\n  \u002F\u002F an index instead of arr.slice(1) and push instead of [...acc, x]:\n  \u002F\u002F copying the array on every step would make it O(n²),\n  \u002F\u002F and acc is created anew on every run and is not visible outside\n  return () => {\n    acc.push(fn (arr[i]))\n    return mapR (fn) (arr, i + 1, acc)\n  }\n}\n\n\u002F\u002F mapTrampoline :: (a -> b) -> [a] -> [b]\n\u002F\u002F from the outside we pass only the array: the index and the accumulator are internal\nconst mapTrampoline = (fn) => (arr) => trampoline (mapR (fn)) (arr)\n\u002F\u002F ===================================\n\n\u002F\u002F ==== run ====\nconst data = [1, 2, 3, 4, 5]\n\nconst result = mapD (v => v * 2) (data)\n\nconsole.log (result) \u002F\u002F [2, 4, 6, 8, 10]\n\u002F\u002F ===================================",{"type":20,"ru":7,"en":31},"filter",{"type":15,"ru":7,"en":33},"The filter function returns a new object of the same data type, passing each element through a predicate function and keeping only the elements for which the predicate returned true (the type is iterable).",{"type":15,"ru":7,"en":35},"A predicate is a function that returns true or false. It is usually passed as an argument to a higher-order function such as filter: in JavaScript functions are first-class values, so they can be passed around like any other value.",{"type":15,"ru":7,"en":37},"Let's implement the filter function in several different ways.",{"type":27,"code":39},{"ru":7,"en":40},"\u002F\u002F currying and taking the data as the last argument\n\u002F\u002F make these functions easy to use in composition\n\u002F\u002F in point-free style, without naming the data:\n\u002F\u002F pipe (mapD (f), filterD (g))\n\n\u002F\u002F ==== declarative implementation ====\n\u002F\u002F filterD :: (a -> Boolean) -> [a] -> [a]\nconst filterD = (fn) => (arr) => arr.filter(fn)\n\u002F\u002F ===================================\n\n\u002F\u002F ==== imperative implementation ====\n\u002F\u002F without the iteration index and context\n\u002F\u002F filterI :: (a -> Boolean) -> [a] -> [a]\nconst filterI = (fn) => (arr) => {\n  \u002F\u002F the resulting array\n  \u002F\u002F that we will return\n  let result = []\n\n  for (const item of arr) {\n    \u002F\u002F pass each element through\n    \u002F\u002F the predicate function\n    \u002F\u002F if it returns true, put the element\n    \u002F\u002F into the resulting array\n    if (fn(item)) {\n      result.push(item) \u002F\u002F or result = [ ...result, item ]\n    }\n  }\n\n  return result\n}\n \u002F\u002F ===================================\n\n\u002F\u002F ==== imperative implementation ====\n\u002F\u002F with the iteration index and context\n\u002F\u002F filterIq :: ((a, Number, [a]) -> Boolean) -> [a] -> [a]\nconst filterIq = (fn) => (arr) => {\n  let result = []\n\n  for (let i = 0; i \u003C arr.length; i++ ) {\n    const value = arr[i]\n\n    if (fn(value, i, arr)) {\n      result.push(value) \u002F\u002F or result = [ ...result, value ]\n    }\n\n  }\n\n  return result\n}\n\u002F\u002F ===================================\n\n\u002F\u002F ==== recursive implementation ====\n\u002F\u002F through a trampoline, so the stack does not overflow\n\u002F\u002F I hope you have read the lesson on recursion\n\n\u002F\u002F trampoline :: ((...args -> *) -> (...args -> *))\n\u002F\u002F calls the function and, while the result is a function (a thunk),\n\u002F\u002F calls it again: the steps run in a loop, the stack does not grow\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 filterR returns either the finished array\n\u002F\u002F or a function with no arguments (a thunk) holding the next step\nconst filterR = (fn) => (arr, i = 0, acc = []) => {\n\n  \u002F\u002F base case\n  \u002F\u002F when the elements run out, return the accumulator\n  if (i === arr.length) {\n    return acc\n  }\n\n  \u002F\u002F recursive case\n  \u002F\u002F return a function for the trampoline\n  return () => {\n     \u002F\u002F the current element\n     const head = arr[i]\n\n     \u002F\u002F put the element into the accumulator\n     \u002F\u002F if the predicate function returned true,\n     \u002F\u002F otherwise the accumulator stays the same\n     if (fn (head)) {\n       acc.push(head)\n     }\n\n     \u002F\u002F move on to the next element\n     \u002F\u002F an index and push instead of [head, ...tail] and [...acc, head]:\n     \u002F\u002F copying the array on every step would make it O(n²)\n     return filterR (fn) (arr, i + 1, acc)\n  }\n}\n\n\u002F\u002F filterTrampoline :: (a -> Boolean) -> [a] -> [a]\n\u002F\u002F from the outside we pass only the array: the index and the accumulator are internal\nconst filterTrampoline = (fn) => (arr) => trampoline (filterR (fn)) (arr)\n\u002F\u002F ===================================\n\n\u002F\u002F ==== run ====\nconst data = [1, 2, 3, 4, 5]\n\nconst result = filterD (v => v > 3) (data)\n\nconsole.log (result) \u002F\u002F [4, 5]\n\u002F\u002F ===================================",{"type":20,"ru":7,"en":42},"reduce",{"type":15,"ru":7,"en":44},"The reduce function can return any data type; it takes a function and an accumulator as its arguments.",{"type":15,"ru":7,"en":46},"As arguments, the function takes the accumulator (from the initial value or from subsequent calls) and the current element, passes this data through the function's logic, and returns a new accumulator or applies changes to the current accumulator.",{"type":15,"ru":7,"en":48},"The accumulator (the initial value) can be any value.",{"type":15,"ru":7,"en":50},"With reduce you can emulate any custom behavior, as well as the behavior of map and filter. But it is usually used to collect specific data according to a particular logic from an iterable object type.",{"type":27,"code":52},{"ru":7,"en":53},"\u002F\u002F currying and taking the data as the last argument\n\u002F\u002F make these functions easy to use in composition\n\u002F\u002F in point-free style, without naming the data:\n\u002F\u002F pipe (mapD (f), filterD (g))\n\n\u002F\u002F ==== declarative implementation ====\n\u002F\u002F reduceD :: ((a, b) -> a) -> a -> [b] -> a\nconst reduceD = (fn) => (init) => (arr) => arr.reduce(fn, init)\n\u002F\u002F ===================================\n\n\u002F\u002F ==== imperative implementation ====\n\u002F\u002F without the iteration index and context\n\u002F\u002F reduceI :: ((a, b) -> a) -> a -> [b] -> a\nconst reduceI = (fn) => (init) => (arr) => {\n\n  \u002F\u002F the value we will return\n  \u002F\u002F starts with the initial value\n  let accumulator = init\n\n  for (const item of arr) {\n    \u002F\u002F call the function\n    \u002F\u002F with the accumulator as the first argument\n    \u002F\u002F and the current array element as the second\n    \u002F\u002F store the result in the accumulator\n    \u002F\u002F so the next call builds on the previous result\n    accumulator = fn (accumulator, item)\n  }\n\n  return accumulator\n}\n \u002F\u002F ===================================\n\n\u002F\u002F ==== imperative implementation ====\n\u002F\u002F with the iteration index and context\n\u002F\u002F reduceIq :: ((a, b, Number, [b]) -> a) -> a -> [b] -> a\nconst reduceIq = (fn) => (init) => (arr) => {\n\n  let accumulator = init\n\n  for (let i = 0; i \u003C arr.length; i++ ) {\n    accumulator = fn (accumulator, arr[i], i, arr)\n  }\n\n  return accumulator\n}\n\u002F\u002F ===================================\n\n\u002F\u002F ==== recursive implementation ====\n\u002F\u002F through a trampoline, so the stack does not overflow\n\u002F\u002F I hope you have read the lesson on recursion\n\n\u002F\u002F trampoline :: ((...args -> *) -> (...args -> *))\n\u002F\u002F calls the function and, while the result is a function (a thunk),\n\u002F\u002F calls it again: the steps run in a loop, the stack does not grow\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 reduceR returns either the final value\n\u002F\u002F or a function with no arguments (a thunk) holding the next step\nconst reduceR = (fn) => (init) => (arr, i = 0) => {\n\n  \u002F\u002F base case\n  \u002F\u002F when the elements run out, return the accumulator\n  if (i === arr.length) {\n    return init\n  }\n\n  \u002F\u002F recursive case\n  \u002F\u002F return a function for the trampoline\n  return () => {\n     \u002F\u002F the accumulator we will return:\n     \u002F\u002F pass the old accumulator and the current value\n     \u002F\u002F through the function\n     const nextInit = fn (init, arr[i])\n\n     \u002F\u002F call the function again\n     \u002F\u002F with the same function,\n     \u002F\u002F the new accumulator\n     \u002F\u002F and the next index: an index instead of [head, ...tail],\n     \u002F\u002F so the array is not copied on every step\n     return reduceR (fn) (nextInit) (arr, i + 1)\n  }\n}\n\n\u002F\u002F reduceTrampoline :: ((a, b) -> a) -> a -> [b] -> a\n\u002F\u002F from the outside we pass only the array: the index is internal\n\u002F\u002F a limitation of the trampoline: if the final value is itself a function,\n\u002F\u002F the trampoline takes it for the next step and calls it\nconst reduceTrampoline = (fn) => (init) => (arr) => trampoline (reduceR (fn) (init)) (arr)\n\u002F\u002F ===================================\n\n\u002F\u002F ==== run ====\nconst data = [1, 2, 3]\n\nconst result = reduceD ((a, b) => a + b) (0) (data)\n\nconsole.log (result) \u002F\u002F 6\n\u002F\u002F ===================================",[55,57,59,61,63],{"ru":7,"en":56},"map returns a new object of the same data type, passing each element through the given function.",{"ru":7,"en":58},"filter returns a new object of the same data type and keeps only the elements for which the predicate returned true.",{"ru":7,"en":60},"reduce takes a function and an accumulator and can return any data type; with it you can emulate both map and filter.",{"ru":7,"en":62},"Currying and taking the data as the last argument let you use these functions in composition in point-free style, without naming the data.",{"ru":7,"en":64},"The recursive versions run through a trampoline and walk the array by index: copying the array on every step would make them O(n²).",[66,75],{"task":67,"starter":69,"solution":71,"expected":73},{"ru":7,"en":68},"The lesson says that reduce can emulate map and filter. Write curried functions mapVia and filterVia that take the data as the last argument and use only reduce inside. Then use pipe to build an onlineNames function from them that returns the names of the users who are online.",{"ru":7,"en":70},"\u002F\u002F pipe from the \"Function composition\" lesson\nconst pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)\n\nconst users = [\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 mapVia :: (a -> b) -> [a] -> [b]\nconst mapVia = (fn) => (arr) => {\n  \u002F\u002F your code\n}\n\n\u002F\u002F filterVia :: (a -> Boolean) -> [a] -> [a]\nconst filterVia = (fn) => (arr) => {\n  \u002F\u002F your code\n}\n\n\u002F\u002F onlineNames :: [Object] -> [String]\nconst onlineNames = pipe(\n  \u002F\u002F your code: filterVia and mapVia\n)\n\nconsole.log(onlineNames(users))\nconsole.log(mapVia((n) => n * 2)([1, 2, 3]))",{"ru":7,"en":72},"\u002F\u002F pipe from the \"Function composition\" lesson\nconst pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)\n\nconst users = [\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 the [] accumulator is created anew on every call and is not visible outside,\n\u002F\u002F so pushing into it changes nobody's data\n\n\u002F\u002F mapVia :: (a -> b) -> [a] -> [b]\n\u002F\u002F pass each element through fn and put the result into the accumulator\nconst mapVia = (fn) => (arr) =>\n  arr.reduce((acc, item) => {\n    acc.push(fn(item))\n    return acc\n  }, [])\n\n\u002F\u002F filterVia :: (a -> Boolean) -> [a] -> [a]\n\u002F\u002F only the elements for which the predicate returned true get into the accumulator\nconst filterVia = (fn) => (arr) =>\n  arr.reduce((acc, item) => {\n    if (fn(item)) {\n      acc.push(item)\n    }\n    return acc\n  }, [])\n\n\u002F\u002F onlineNames :: [Object] -> [String]\n\u002F\u002F point-free style: we don't name the data, it comes into pipe last\nconst onlineNames = pipe(\n  filterVia((user) => user.status === 'online'),\n  mapVia((user) => user.name),\n)\n\nconsole.log(onlineNames(users))\nconsole.log(mapVia((n) => n * 2)([1, 2, 3]))",{"ru":7,"en":74},"[\n  \"John\",\n  \"Angel\"\n]\n[\n  2,\n  4,\n  6\n]",{"task":76,"starter":78,"solution":80,"expected":82},{"ru":7,"en":77},"reduce can return any data type, an object for example. Write a curried function countBy: its first argument is a function that returns an element's key, its second is an array, and it uses reduce to return an object that shows, for each key, how many elements produced it. Count the users by status, and the numbers from 1 to 5 by parity.",{"ru":7,"en":79},"const users = [\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 countBy :: (a -> String) -> [a] -> Object\nconst countBy = (fn) => (arr) => {\n  \u002F\u002F your code\n}\n\nconsole.log(countBy((user) => user.status)(users))\nconsole.log(countBy((n) => (n % 2 === 0 ? 'even' : 'odd'))([1, 2, 3, 4, 5]))",{"ru":7,"en":81},"const users = [\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 countBy :: (a -> String) -> [a] -> Object\n\u002F\u002F the accumulator is a {} object, created anew on every call\nconst countBy = (fn) => (arr) =>\n  arr.reduce((acc, item) => {\n    \u002F\u002F the key of the current element\n    const key = fn(item)\n    \u002F\u002F a key gets 1 the first time, then its counter grows by one\n    acc[key] = (acc[key] ?? 0) + 1\n    return acc\n  }, {})\n\nconsole.log(countBy((user) => user.status)(users))\nconsole.log(countBy((n) => (n % 2 === 0 ? 'even' : 'odd'))([1, 2, 3, 4, 5]))",{"ru":7,"en":83},"{\n  \"online\": 2,\n  \"offline\": 2\n}\n{\n  \"odd\": 3,\n  \"even\": 2\n}",14,{"slug":86,"title":87},"recursion",{"ru":7,"en":88},"Recursion",{"slug":90,"title":91},"performance",{"ru":7,"en":92},"Performance",1792684724643]