[{"data":1,"prerenderedAt":78},["ShallowReactive",2],{"course-en-side-effects-in-composition-functions":3},{"lesson":4,"number":69,"prev":70,"next":74},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":41,"exercises":50},"side-effects-in-composition-functions",{"ru":7,"en":8},"","Side effects in function composition",{"ru":7,"en":10},"How to add a side effect to a JavaScript function composition without breaking the chain: tap for logging pipe steps and for actions the program needs.",{"ru":7,"en":12},"Learn to add side effects to a function composition, such as logging for debugging or actions the program logic requires, so that the data keeps flowing down the chain unchanged.",[14,17,19,27,29,33,35,37],{"type":15,"ru":7,"en":16},"text","Based on the principles of functional programming, one might think that creating side effects within function composition is forbidden. But in reality, any program, and especially web development, will create some side effect no matter what (DOM operations, input\u002Foutput operations, logging, and so on ...).",{"type":15,"ru":7,"en":18},"In real-world cases, side effects within function composition can be useful to us mainly in two situations:",{"type":20,"ordered":21,"items":22},"list",true,[23,25],{"ru":7,"en":24},"Debugging the composition and logging it, in case of errors or simply to understand the execution flow and how the input data changes within the function composition.",{"ru":7,"en":26},"Creating a side effect within the program according to its logic and continuing the execution of the function composition.",{"type":15,"ru":7,"en":28},"Let's try to inspect the intermediate results within a function composition by creating a side effect in the form of logging the data.",{"type":30,"code":31},"code",{"ru":7,"en":32},"\u002F\u002F A program that takes the user's money,\n\u002F\u002F compares it with the product price\n\u002F\u002F and reports whether the user can afford the product\n\u002F\u002F ===============================\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (data) =>\n                              fns\n                                .reduce((init, fn) => fn(init), data)\n\n\u002F\u002F a test user with $10,000\nconst dataUser = {\n  name: 'John',\n  money: 10000,\n}\n\n\u002F\u002F a product priced at $8,000\nconst product = {\n  name: 'car',\n  model: 'toyota',\n  price: 8000\n}\n\n\u002F\u002F prop :: String -> Record -> a\nconst prop = (prop) => (data) => data[prop]\n\n\u002F\u002F lte :: Number -> Number -> Boolean\nconst lte = (a) => (b) => a \u003C= b\n\nconst pipeline = pipe(\n  prop ('money'), \u002F\u002F get the user's money\n  lte (prop ('price') (product)), \u002F\u002F check that the product price is not greater than the user's money\n  (success) => success ? 'the product can be purchased' : \"you don't have enough money\"\n  \u002F\u002F report whether the user can buy the product or lacks the money\n)\n\n\u002F\u002F run the composition\nconst resultMsg = pipeline (dataUser)\n\nconsole.log(resultMsg) \u002F\u002F the product can be purchased",{"type":15,"ru":7,"en":34},"But how do we obtain the results of each function call in pipeline (prop ('money') ...), if there won't even be any errors in the composition and we simply want to debug the code.",{"type":15,"ru":7,"en":36},"Let's write a universal utility for any case in the chain of composition calls.",{"type":30,"noRun":38,"code":39},"previous-block",{"ru":7,"en":40},"\u002F\u002F A utility that calls the function it was given\n\u002F\u002F and passes the argument further down the composition\n\u002F\u002F ===============================\n\u002F\u002F tapD :: (a -> *) -> a -> a\nconst tapD = (fn) => (arg) => {\n\n  \u002F\u002F check that the first argument\n  \u002F\u002F really is a function\n  if (typeof fn === 'function') {\n    \u002F\u002F call the function with the argument\n    fn (arg)\n  }\n\n  \u002F\u002F don't forget to pass the argument on\n  \u002F\u002F to the next call in the composition\n  return arg\n}\n\n\u002F\u002F it can be shortened to one line\n\u002F\u002F tap :: (a -> *) -> a -> a\nconst tap = (fn) => (arg) => (fn (arg), arg)\n\n\u002F\u002F now let's prepare a utility\n\u002F\u002F that logs the data\n\u002F\u002F after each call in the composition\n\n\u002F\u002F standard console output\nconst log = console.log\n\n\u002F\u002F create the logger\nconst logger = tap (log)\n\n\u002F\u002F put the logger into the chain of function calls\n\u002F\u002F and run the chain right away\npipe(\n  prop ('money'),\n  logger, \u002F\u002F 10000\n  lte (prop ('price') (product)),\n  logger, \u002F\u002F true\n  (success) => success ? 'the product can be purchased' : \"you don't have enough money\",\n  logger, \u002F\u002F 'the product can be purchased'\n) (dataUser)",[42,44,46,48],{"ru":7,"en":43},"Any program, and especially web development, creates side effects: DOM operations, input and output, logging.",{"ru":7,"en":45},"In function composition, side effects are needed mainly in two cases: for debugging and logging, and for actions the program logic requires, after which the composition keeps running.",{"ru":7,"en":47},"The tap :: (a -> *) -> a -> a utility calls the given function with the argument and returns that same argument, so the next function in the composition receives the data unchanged.",{"ru":7,"en":49},"A logger built as tap (console.log) and placed between the steps of pipe prints the intermediate result after each call.",[51,60],{"task":52,"starter":54,"solution":56,"expected":58},{"ru":7,"en":53},"To debug the total pipeline, someone put console.log straight between its steps, and the pipeline broke: console.log returns undefined, and the next step receives it instead of the data. Write tap and a labelled logger tapLog :: String -> a -> a that prints the line \"label: value\" (the value via JSON.stringify) and returns its argument unchanged. Put tapLog after each step of total instead of console.log, with the labels \"items\", \"sum\" and \"discounted\".",{"ru":7,"en":55},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (data) => fns.reduce((acc, fn) => fn(acc), data)\n\n\u002F\u002F the cart: price and quantity of each item\nconst cart = [\n  { name: 'book', price: 20, qty: 2 },\n  { name: 'pen', price: 5, qty: 4 },\n  { name: 'bag', price: 50, qty: 1 },\n]\n\n\u002F\u002F your code: tap and tapLog\n\n\u002F\u002F total :: [Object] -> Number\nconst total = pipe(\n  (items) => items.map((item) => item.price * item.qty), \u002F\u002F the cost of each item\n  console.log, \u002F\u002F debugging: prints, but returns undefined\n  (sums) => sums.reduce((sum, x) => sum + x, 0), \u002F\u002F the total sum\n  (sum) => (sum > 100 ? sum - 10 : sum), \u002F\u002F a discount of 10 if the sum is over 100\n)\n\nconsole.log(total(cart))",{"ru":7,"en":57},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (data) => fns.reduce((acc, fn) => fn(acc), data)\n\n\u002F\u002F the cart: price and quantity of each item\nconst cart = [\n  { name: 'book', price: 20, qty: 2 },\n  { name: 'pen', price: 5, qty: 4 },\n  { name: 'bag', price: 50, qty: 1 },\n]\n\n\u002F\u002F tap :: (a -> *) -> a -> a\nconst tap = (fn) => (arg) => (fn(arg), arg)\n\n\u002F\u002F a labelled logger: prints the value and returns it unchanged\n\u002F\u002F tapLog :: String -> a -> a\nconst tapLog = (label) => tap((value) => console.log(`${label}: ${JSON.stringify(value)}`))\n\n\u002F\u002F total :: [Object] -> Number\nconst total = pipe(\n  (items) => items.map((item) => item.price * item.qty), \u002F\u002F the cost of each item\n  tapLog('items'),\n  (sums) => sums.reduce((sum, x) => sum + x, 0), \u002F\u002F the total sum\n  tapLog('sum'),\n  (sum) => (sum > 100 ? sum - 10 : sum), \u002F\u002F a discount of 10 if the sum is over 100\n  tapLog('discounted'),\n)\n\nconsole.log(total(cart))",{"ru":7,"en":59},"items: [40,20,50]\nsum: 110\ndiscounted: 100\n100",{"task":61,"starter":63,"solution":65,"expected":67},{"ru":7,"en":62},"The second case is a side effect the program logic requires. Write tapWhen :: (a -> Boolean) -> (a -> *) -> a -> a: it calls the effect function only if the predicate returned true, and returns the argument in any case. Use it at the start of the checkout pipeline to add the user's name to the declined log when they don't have enough money for the product. The composition must still run to the end and return a message.",{"ru":7,"en":64},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (data) => fns.reduce((acc, fn) => fn(acc), data)\n\n\u002F\u002F tap :: (a -> *) -> a -> a\nconst tap = (fn) => (arg) => (fn(arg), arg)\n\n\u002F\u002F your code: tapWhen\n\n\u002F\u002F the product\nconst product = { name: 'car', price: 8000 }\n\n\u002F\u002F the log: who didn't have enough money\nconst declined = []\n\n\u002F\u002F checkout :: Object -> String\nconst checkout = pipe(\n  \u002F\u002F your code: add to the declined log\n  (user) => user.money >= product.price, \u002F\u002F is there enough money\n  (success) => (success ? 'the product can be purchased' : \"you don't have enough money\"),\n)\n\nconst users = [\n  { name: 'John', money: 10000 },\n  { name: 'Anna', money: 5000 },\n  { name: 'Mike', money: 8000 },\n]\n\nusers.map(checkout).forEach((message) => console.log(message))\nconsole.log(`not enough money: ${declined.join(', ')}`)",{"ru":7,"en":66},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (data) => fns.reduce((acc, fn) => fn(acc), data)\n\n\u002F\u002F tap :: (a -> *) -> a -> a\nconst tap = (fn) => (arg) => (fn(arg), arg)\n\n\u002F\u002F the effect fires only on the condition; the argument always moves on\n\u002F\u002F tapWhen :: (a -> Boolean) -> (a -> *) -> a -> a\nconst tapWhen = (pred) => (fn) => tap((arg) => {\n  if (pred(arg)) fn(arg)\n})\n\n\u002F\u002F the product\nconst product = { name: 'car', price: 8000 }\n\n\u002F\u002F the log: who didn't have enough money\nconst declined = []\n\n\u002F\u002F checkout :: Object -> String\nconst checkout = pipe(\n  tapWhen((user) => user.money \u003C product.price)((user) => declined.push(user.name)),\n  (user) => user.money >= product.price, \u002F\u002F is there enough money\n  (success) => (success ? 'the product can be purchased' : \"you don't have enough money\"),\n)\n\nconst users = [\n  { name: 'John', money: 10000 },\n  { name: 'Anna', money: 5000 },\n  { name: 'Mike', money: 8000 },\n]\n\nusers.map(checkout).forEach((message) => console.log(message))\nconsole.log(`not enough money: ${declined.join(', ')}`)",{"ru":7,"en":68},"the product can be purchased\nyou don't have enough money\nthe product can be purchased\nnot enough money: Anna",19,{"slug":71,"title":72},"lenses",{"ru":7,"en":73},"Lenses",{"slug":75,"title":76},"category-theory",{"ru":7,"en":77},"Category theory",1792684725066]