[{"data":1,"prerenderedAt":94},["ShallowReactive",2],{"course-en-transducers":3},{"lesson":4,"number":85,"prev":86,"next":90},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":55,"exercises":66},"transducers",{"ru":7,"en":8},"","Transducers",{"ru":7,"en":10},"Transducers in JavaScript: map and filter without intermediate arrays, reducers and reducer transformers, step order in R.compose, R.transduce and R.into.",{"ru":7,"en":12},"Understand why a map and filter chain creates intermediate arrays, learn to write transducers as reducer transformers, compose them with compose, use R.transduce and R.into, and judge when it pays off.",[14,17,21,23,26,28,30,33,35,37,39,42,44,46,49,51,53],{"type":15,"ru":7,"en":16},"text","A map and filter chain reads well, but it has a cost. Each step walks the whole array and creates a new one. filter(isEven), map(square), filter(isBig) means three passes and three new arrays, two of them intermediate: they are needed only as input for the next step. In the \"Performance\" lesson we already counted this overhead in callback calls; now let's count the arrays too.",{"type":18,"code":19},"code",{"ru":7,"en":20},"\u002F\u002F counters: how many arrays were created and how many times the steps were called\nconst stats = { arrays: 0, calls: 0 }\n\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst map = (fn) => (arr) => {\n  stats.arrays += 1\n  return arr.map((x) => {\n    stats.calls += 1\n    return fn(x)\n  })\n}\n\u002F\u002F filter :: (a -> Boolean) -> [a] -> [a]\nconst filter = (pred) => (arr) => {\n  stats.arrays += 1\n  return arr.filter((x) => {\n    stats.calls += 1\n    return pred(x)\n  })\n}\n\n\u002F\u002F isEven :: Number -> Boolean\nconst isEven = (n) => n % 2 === 0\n\u002F\u002F square :: Number -> Number\nconst square = (n) => n * n\n\u002F\u002F isBig :: Number -> Boolean\nconst isBig = (n) => n > 100000\n\n\u002F\u002F the numbers from 1 to 1000\nconst numbers = R.range(1, 1001)\n\nconst result = R.pipe(filter(isEven), map(square), filter(isBig))(numbers)\n\nconsole.log('numbers in the result: ' + result.length) \u002F\u002F numbers in the result: 342\n\u002F\u002F 1000 calls of the first filter, 500 calls of map and 500 calls of the second filter\nconsole.log('arrays: ' + stats.arrays + ', calls: ' + stats.calls) \u002F\u002F arrays: 3, calls: 2000",{"type":15,"ru":7,"en":22},"You could merge all the steps into a single reduce, as in the exercise of the \"Performance\" lesson, but then they would fuse into one callback and stop being separate functions. Transducers give you both: the steps stay separate and composable, and the data goes through them in a single pass, with no intermediate arrays. The idea comes from Clojure, where Rich Hickey proposed transducers in 2014.",{"type":24,"ru":7,"en":25},"heading","A reducer and a reducer transformer",{"type":15,"ru":7,"en":27},"A reducer is the function that reduce takes: (acc, x) => newAcc. It receives the accumulated value and the next element and returns the new accumulated value. Summing is a reducer, and so is appending an element to an array.",{"type":15,"ru":7,"en":29},"A transducer is a reducer transformer: a function that takes a reducer and returns a new reducer. mapping(f) turns a reducer into one that applies f to the element first, and filtering(pred) turns it into one that lets only matching elements through to the original reducer. Neither of them knows what the reducer does: collects an array, computes a sum or builds a string.",{"type":18,"code":31},{"ru":7,"en":32},"\u002F\u002F === reducers: (acc, x) -> acc ===\n\u002F\u002F pushTo :: ([a], a) -> [a]\n\u002F\u002F changes only the accumulator we created for this fold;\n\u002F\u002F copying [...acc, x] on every step would mean quadratic work\nconst pushTo = (acc, x) => {\n  acc.push(x)\n  return acc\n}\n\u002F\u002F sum :: (Number, Number) -> Number\nconst sum = (acc, x) => acc + x\n\n\u002F\u002F === transducers: take a reducer and return a reducer ===\n\u002F\u002F mapping :: (a -> b) -> ((acc, b) -> acc) -> ((acc, a) -> acc)\nconst mapping = (fn) => (reducer) => (acc, x) => reducer(acc, fn(x))\n\u002F\u002F filtering :: (a -> Boolean) -> ((acc, a) -> acc) -> ((acc, a) -> acc)\nconst filtering = (pred) => (reducer) => (acc, x) => (pred(x) ? reducer(acc, x) : acc)\n\n\u002F\u002F isEven :: Number -> Boolean\nconst isEven = (n) => n % 2 === 0\n\u002F\u002F square :: Number -> Number\nconst square = (n) => n * n\n\n\u002F\u002F by hand: mapping wraps pushTo, filtering wraps the result\nconst evenSquaresToArray = filtering(isEven)(mapping(square)(pushTo))\nconsole.log([1, 2, 3, 4, 5, 6].reduce(evenSquaresToArray, []).join(', ')) \u002F\u002F 4, 16, 36\n\n\u002F\u002F the same steps with another reducer: a sum instead of an array\nconst evenSquaresSum = filtering(isEven)(mapping(square)(sum))\nconsole.log([1, 2, 3, 4, 5, 6].reduce(evenSquaresSum, 0)) \u002F\u002F 56",{"type":24,"ru":7,"en":34},"Composing transducers",{"type":15,"ru":7,"en":36},"A transducer is a function of one argument, so transducers compose with compose. The order of writing is unusual here: in compose(filtering(isEven), mapping(square)) the elements are filtered first and only then squared. The steps run left to right, as in pipe.",{"type":15,"ru":7,"en":38},"Here is why. compose does apply functions right to left, but it applies them to the reducer, not to the data. First mapping(square) wraps the final reducer, then filtering(isEven) wraps the result. The leftmost wrapper ends up outermost, and every element reaches it first. The wrappers are built right to left, and the data goes through them left to right.",{"type":18,"code":40},{"ru":7,"en":41},"\u002F\u002F compose :: ((y -> z), ..., (a -> b)) -> a -> z\nconst compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x)\n\n\u002F\u002F transduce :: (transducer, reducer, acc, [a]) -> acc\nconst transduce = (xform, reducer, init, arr) => arr.reduce(xform(reducer), init)\n\n\u002F\u002F mapping and filtering from the previous example\nconst mapping = (fn) => (reducer) => (acc, x) => reducer(acc, fn(x))\nconst filtering = (pred) => (reducer) => (acc, x) => (pred(x) ? reducer(acc, x) : acc)\n\n\u002F\u002F counters: arrays are created only with newArray, counted counts the steps\nconst stats = { arrays: 0, calls: 0 }\nconst newArray = () => {\n  stats.arrays += 1\n  return []\n}\nconst counted = (fn) => (x) => {\n  stats.calls += 1\n  return fn(x)\n}\n\nconst pushTo = (acc, x) => {\n  acc.push(x)\n  return acc\n}\nconst isEven = (n) => n % 2 === 0\nconst square = (n) => n * n\nconst isBig = (n) => n > 100000\n\n\u002F\u002F the steps are written in the order they run: filter, map, filter\nconst xform = compose(\n  filtering(counted(isEven)),\n  mapping(counted(square)),\n  filtering(counted(isBig)),\n)\n\nconst result = transduce(xform, pushTo, newArray(), R.range(1, 1001))\n\nconsole.log('numbers in the result: ' + result.length) \u002F\u002F numbers in the result: 342\n\u002F\u002F one pass, one array (the accumulator), and as many step calls as in the chain\nconsole.log('arrays: ' + stats.arrays + ', calls: ' + stats.calls) \u002F\u002F arrays: 1, calls: 2000",{"type":24,"ru":7,"en":43},"Transducers in Ramda",{"type":15,"ru":7,"en":45},"In Ramda, map, filter, take and a number of other list functions work as transducers if you call them without data and pass the result to R.transduce or R.into. R.transduce(xform, reducer, init, list) is a fold like our transduce: you supply the reducer and the initial value. R.into(acc, xform, list) picks the reducer from its first argument: elements are appended to an array, concatenated to a string, or have their properties or [key, value] pairs copied into an object. Note that in Ramda 0.32 only the type of the first argument is used, and its contents do not make it into the result: R.into([1, 2], R.map(R.inc), [3]) returns [4], not [1, 2, 4]. So pass an empty value: [], '' or {}. The Ramda docs call an object with the @@transducer\u002Finit, @@transducer\u002Fstep and @@transducer\u002Fresult methods a transformer, and a function that takes such a transformer and returns a new one a transducer. The idea is the same, just with an object instead of a reducer function.",{"type":18,"code":47},{"ru":7,"en":48},"\u002F\u002F isEven :: Number -> Boolean\nconst isEven = (n) => n % 2 === 0\n\u002F\u002F the numbers from 1 to 10\nconst numbers = R.range(1, 11)\n\n\u002F\u002F R.filter and R.map without data are transducers\nconst xform = R.compose(R.filter(isEven), R.map((n) => n * n))\n\n\u002F\u002F R.into: the result has the same shape as the first argument\nconsole.log(R.into([], xform, numbers).join(', ')) \u002F\u002F 4, 16, 36, 64, 100\nconsole.log(R.into('', R.compose(xform, R.map((n) => n + ';')), numbers)) \u002F\u002F 4;16;36;64;100;\n\u002F\u002F R.transduce: your own reducer and initial value\nconsole.log(R.transduce(xform, R.add, 0, numbers)) \u002F\u002F 220\n\n\u002F\u002F === one composition, two orders ===\nconst incThenKeepEven = R.compose(R.map(R.inc), R.filter(isEven))\n\u002F\u002F as a plain function on an array: compose goes right to left, filter first, then map\nconsole.log(incThenKeepEven([1, 2, 3, 4]).join(', ')) \u002F\u002F 3, 5\n\u002F\u002F as a transducer: left to right, map first, then filter\nconsole.log(R.into([], incThenKeepEven, [1, 2, 3, 4]).join(', ')) \u002F\u002F 2, 4\n\n\u002F\u002F === stopping early ===\nlet chainCalls = 0\nconst chainResult = R.range(1, 1001)\n  .map((n) => {\n    chainCalls += 1\n    return n * n\n  })\n  .filter((n) => n > 100)\n  .slice(0, 3)\nconsole.log(chainResult.join(', ') + ', map calls: ' + chainCalls) \u002F\u002F 121, 144, 169, map calls: 1000\n\nlet xformCalls = 0\nconst firstThree = R.compose(\n  R.map((n) => {\n    xformCalls += 1\n    return n * n\n  }),\n  R.filter((n) => n > 100),\n  R.take(3), \u002F\u002F three elements taken: the fold stops\n)\nconsole.log(R.into([], firstThree, R.range(1, 1001)).join(', ') + ', map calls: ' + xformCalls) \u002F\u002F 121, 144, 169, map calls: 13",{"type":24,"ru":7,"en":50},"When it pays off",{"type":15,"ru":7,"en":52},"On a full pass transducers don't reduce the number of step calls: every element goes through every step it reaches, just as in the chain. The gain is elsewhere. There are no intermediate arrays and no extra passes. The fold can stop early, as with R.take. The same transformation works with any reducer and any source Ramda's fold understands: an array, an iterable such as a Set or a generator, or an object with a reduce method.",{"type":15,"ru":7,"en":54},"This shows on large collections, long chains and early stopping. For an array of a hundred elements and two steps, a map and filter chain is easier to read and fast enough. ES2025 gave iterators their own lazy map, filter and take methods: they also handle elements one by one, with no intermediate arrays. Transducers differ in that they separate the transformation both from the data source and from the way the result is collected. As in the \"Performance\" lesson, check the gain by measuring: count arrays and calls, or repeat time measurements, rather than relying on a single run.",[56,58,60,62,64],{"ru":7,"en":57},"Each step of a map and filter chain walks the whole array and creates a new one; the intermediate arrays are needed only as input for the next step.",{"ru":7,"en":59},"A reducer is a function (acc, x) => acc, and a transducer is a reducer transformer: it takes a reducer and returns a new one without knowing what that reducer collects.",{"ru":7,"en":61},"compose applies transducers to the reducer right to left, so the leftmost wrapper ends up outermost and the data goes through the steps left to right.",{"ru":7,"en":63},"In Ramda, map, filter and take without data work as transducers: R.transduce folds with your reducer, and R.into collects the result into an array, a string or an object.",{"ru":7,"en":65},"Transducers remove intermediate arrays and extra passes and can stop early; on small arrays and short chains a plain chain is simpler.",[67,76],{"task":68,"starter":70,"solution":72,"expected":74},{"ru":7,"en":69},"Write the mapping and filtering transducers and use compose to build the paidTotals transducer from them: keep the paid orders, take their total, keep the totals of 1000 and more. Apply it to the two reducers from the starter: with pushTo you get an array of totals, with sum their grand total. Think about the order in which to write the steps in compose.",{"ru":7,"en":71},"const orders = [\n  { id: 1, total: 1200, paid: true },\n  { id: 2, total: 300, paid: false },\n  { id: 3, total: 4500, paid: true },\n  { id: 4, total: 800, paid: true },\n  { id: 5, total: 2500, paid: false },\n]\n\n\u002F\u002F compose :: ((y -> z), ..., (a -> b)) -> a -> z\nconst compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x)\n\n\u002F\u002F reducers\n\u002F\u002F pushTo :: ([a], a) -> [a]\nconst pushTo = (acc, x) => {\n  acc.push(x)\n  return acc\n}\n\u002F\u002F sum :: (Number, Number) -> Number\nconst sum = (acc, x) => acc + x\n\n\u002F\u002F your code: mapping, filtering and paidTotals\n\nconsole.log(orders.reduce(paidTotals(pushTo), []).join(', '))\nconsole.log(orders.reduce(paidTotals(sum), 0))",{"ru":7,"en":73},"const orders = [\n  { id: 1, total: 1200, paid: true },\n  { id: 2, total: 300, paid: false },\n  { id: 3, total: 4500, paid: true },\n  { id: 4, total: 800, paid: true },\n  { id: 5, total: 2500, paid: false },\n]\n\n\u002F\u002F compose :: ((y -> z), ..., (a -> b)) -> a -> z\nconst compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x)\n\n\u002F\u002F reducers\n\u002F\u002F pushTo :: ([a], a) -> [a]\nconst pushTo = (acc, x) => {\n  acc.push(x)\n  return acc\n}\n\u002F\u002F sum :: (Number, Number) -> Number\nconst sum = (acc, x) => acc + x\n\n\u002F\u002F mapping :: (a -> b) -> ((acc, b) -> acc) -> ((acc, a) -> acc)\nconst mapping = (fn) => (reducer) => (acc, x) => reducer(acc, fn(x))\n\u002F\u002F filtering :: (a -> Boolean) -> ((acc, a) -> acc) -> ((acc, a) -> acc)\nconst filtering = (pred) => (reducer) => (acc, x) => (pred(x) ? reducer(acc, x) : acc)\n\n\u002F\u002F the steps are written in the order they run: the leftmost wrapper is outermost,\n\u002F\u002F so an order is checked for payment first and then turned into its total\nconst paidTotals = compose(\n  filtering((order) => order.paid),\n  mapping((order) => order.total),\n  filtering((total) => total >= 1000),\n)\n\nconsole.log(orders.reduce(paidTotals(pushTo), []).join(', '))\nconsole.log(orders.reduce(paidTotals(sum), 0))",{"ru":7,"en":75},"1200, 4500\n5700",{"task":77,"starter":79,"solution":81,"expected":83},{"ru":7,"en":78},"In the starter, the names of the first three active users are found with a chain of filter, map and slice over a list of 1000 users, and a counter shows how many times the predicate was called. Rewrite the search with R.into, R.compose, R.filter, R.map and R.take using the isActive predicate, and compare the number of calls.",{"ru":7,"en":80},"\u002F\u002F 1000 users, every seventh one is active\nconst users = R.range(1, 1001).map((id) => ({ id, name: 'user' + id, active: id % 7 === 0 }))\n\nlet chainCalls = 0\nconst isActiveChain = (user) => {\n  chainCalls += 1\n  return user.active\n}\nconst chainResult = users.filter(isActiveChain).map((user) => user.name).slice(0, 3)\nconsole.log('chain: ' + chainResult.join(', ') + ', calls: ' + chainCalls)\n\nlet xformCalls = 0\nconst isActive = (user) => {\n  xformCalls += 1\n  return user.active\n}\n\u002F\u002F your code: xformResult with R.into\nconst xformResult = []\n\nconsole.log('transducer: ' + xformResult.join(', ') + ', calls: ' + xformCalls)",{"ru":7,"en":82},"\u002F\u002F 1000 users, every seventh one is active\nconst users = R.range(1, 1001).map((id) => ({ id, name: 'user' + id, active: id % 7 === 0 }))\n\nlet chainCalls = 0\nconst isActiveChain = (user) => {\n  chainCalls += 1\n  return user.active\n}\nconst chainResult = users.filter(isActiveChain).map((user) => user.name).slice(0, 3)\nconsole.log('chain: ' + chainResult.join(', ') + ', calls: ' + chainCalls)\n\nlet xformCalls = 0\nconst isActive = (user) => {\n  xformCalls += 1\n  return user.active\n}\n\u002F\u002F the steps in the order they run: select, take the name, stop at the third one\nconst firstActiveNames = R.compose(R.filter(isActive), R.map(R.prop('name')), R.take(3))\nconst xformResult = R.into([], firstActiveNames, users)\n\n\u002F\u002F the predicate checked users 1 to 21: at user21 R.take had collected three names\nconsole.log('transducer: ' + xformResult.join(', ') + ', calls: ' + xformCalls)",{"ru":7,"en":84},"chain: user7, user14, user21, calls: 1000\ntransducer: user7, user14, user21, calls: 21",17,{"slug":87,"title":88},"memoization",{"ru":7,"en":89},"Memoization",{"slug":91,"title":92},"lenses",{"ru":7,"en":93},"Lenses",1792684725060]