[{"data":1,"prerenderedAt":66},["ShallowReactive",2],{"course-en-pure-functions":3},{"lesson":4,"number":57,"prev":58,"next":62},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":27,"exercises":38},"pure-functions",{"ru":7,"en":8},"","Pure functions",{"ru":7,"en":10},"How to tell a pure function from an impure one in JavaScript and return a new object with spread or structuredClone instead of mutating outside data.",{"ru":7,"en":12},"Learn to tell pure functions from impure ones and to rewrite impure ones so that they return a new value instead of mutating outside data.",[14,17,21,24],{"type":15,"ru":7,"en":16},"text","Pure functions are extremely important. A pure function is not necessarily idempotent, though: x => x + 1 is pure, but applying it to its own result gives a new value. If you need side effects, group them into separate functions and keep them apart from pure functions. Every program, especially on the web, needs side effects (mutating the DOM tree, requests to the server (fetch), reading from a file (readFile), and so on).",{"type":18,"code":19},"code",{"ru":7,"en":20},"\u002F\u002F An IMpure function\n\u002F\u002F ===============================\nlet user = { name: 'John', age: 25 }\n\nconst changeAge = () => user.age = 30\n\n\u002F\u002F we mutate an outer variable and create side effects\n\u002F\u002F the program will behave unpredictably, since several functions\n\u002F\u002F may work with this variable, and a bug will be harder to track down\nchangeAge()\nconsole.log(user) \u002F\u002F { name: 'John', age: 30 }\n\u002F\u002F ===============================",{"type":18,"code":22},{"ru":7,"en":23},"\u002F\u002F Code like this is acceptable if we create independent modules with their own closure\n\u002F\u002F ===============================\n\u002F\u002F useChangeUser :: Object -> Object\nconst useChangeUser = (user) => {\n\n  let userBase = structuredClone(user) \u002F\u002F be sure to clone\n\n  const changeAge = (newAge) => userBase.age = newAge\n\n  \u002F\u002F to work with the data from outside\n  return {\n    userBase,\n    changeAge\n  }\n}\n\n\u002F\u002F But even in this case it is better to do this\n\u002F\u002F useImmutableUser :: Object -> Object\nconst useImmutableUser = (user) => {\n\n  let userBase = structuredClone(user) \u002F\u002F be sure to clone\n\n  const changeAge = (newAge) => userBase = ({\n    ...userBase, \u002F\u002F or structuredClone(userBase) or JSON.parse(JSON.stringify(userBase))\n    age: newAge\n  })\n\n  \u002F\u002F to work with the data from outside\n  \u002F\u002F getUser always returns the current object: changeAge replaces it with a new one\n  return {\n    getUser: () => userBase,\n    changeAge\n  }\n}\n\nconst john = useImmutableUser({ name: 'John', age: 25 })\nconst before = john.getUser()\njohn.changeAge(30)\nconsole.log(john.getUser()) \u002F\u002F { name: 'John', age: 30 } the change is visible from outside\nconsole.log(before) \u002F\u002F { name: 'John', age: 25 } the previous object has not changed\n\u002F\u002F ===============================",{"type":18,"code":25},{"ru":7,"en":26},"\u002F\u002F Now let's fix the example above\n\u002F\u002F ===============================\nlet user = { name: 'John', age: 25 }\n\n\u002F\u002F A pure function\n\u002F\u002F changeAge :: (Number, Object) -> Object\nconst changeAge = (newAge, user) => ({\n  ...user,\n  age: newAge\n})\n\n\u002F\u002F  let's improve it\n\u002F\u002F in case we need deep cloning and currying\n\n\u002F\u002F changeAgeCurried :: Number -> Object -> Object\nconst changeAgeCurried = (newAge) => (user) => ({\n  ...structuredClone(user), \u002F\u002F or JSON.parse(JSON.stringify(user))\n  age: newAge\n})\n\n\u002F\u002F let's check everything here\nconst changedUser = changeAgeCurried (30) (user)\n\nconsole.log(user) \u002F\u002F { name: 'John', age: 25 } kept its original state\nconsole.log(changedUser) \u002F\u002F { name: 'John', age: 30 } we got a new user without side effects\n\u002F\u002F ===============================",[28,30,32,34,36],{"ru":7,"en":29},"A pure function is not necessarily idempotent: x => x + 1 is pure, but applying it to its own result gives a new value.",{"ru":7,"en":31},"Every program, especially on the web, needs side effects: mutating the DOM, requests to the server, reading from a file. Group them into separate functions and keep them apart from pure functions.",{"ru":7,"en":33},"A function that mutates an outer variable creates side effects: several functions may work with that variable, and a bug will be harder to track down.",{"ru":7,"en":35},"A pure function does not change the object passed to it but returns a new one: with spread, or with structuredClone if deep cloning is needed.",{"ru":7,"en":37},"Even in a module with its own closure, it is better to replace the state with a new object than to mutate it.",[39,48],{"task":40,"starter":42,"solution":44,"expected":46},{"ru":7,"en":41},"The addTagImpure function changes the post passed to it. Write a pure addTag: it returns a new post with the tag added and leaves the original alone. Keep in mind that tags is a nested array: if you copy only the object itself, the array stays shared.",{"ru":7,"en":43},"\u002F\u002F addTagImpure :: (String, Object) -> Object\n\u002F\u002F IMpure: it changes the post passed to it\nconst addTagImpure = (tag, post) => {\n  post.tags.push(tag)\n  return post\n}\n\n\u002F\u002F addTag :: (String, Object) -> Object\n\u002F\u002F your code\n\nconst post = { title: 'FP', tags: ['js'] }\nconst taggedPost = addTag('fp', post)\n\nconsole.log(post.tags) \u002F\u002F the original post has not changed\nconsole.log(taggedPost.tags)",{"ru":7,"en":45},"\u002F\u002F addTagImpure :: (String, Object) -> Object\n\u002F\u002F IMpure: it changes the post passed to it\nconst addTagImpure = (tag, post) => {\n  post.tags.push(tag)\n  return post\n}\n\n\u002F\u002F addTag :: (String, Object) -> Object\n\u002F\u002F Pure: a new object and a new tags array, the original post is not changed\nconst addTag = (tag, post) => ({\n  ...post,\n  tags: [...post.tags, tag],\n})\n\nconst post = { title: 'FP', tags: ['js'] }\nconst taggedPost = addTag('fp', post)\n\nconsole.log(post.tags) \u002F\u002F the original post has not changed\nconsole.log(taggedPost.tags)",{"ru":7,"en":47},"[\n  \"js\"\n]\n[\n  \"js\",\n  \"fp\"\n]",{"task":49,"starter":51,"solution":53,"expected":55},{"ru":7,"en":50},"The result of finalPriceImpure depends on the outer variable discount: with the same argument, the function returns a different price once discount has changed. Write a pure finalPrice that receives the discount percentage as an argument. Run the code and compare the lines before and after discount changes.",{"ru":7,"en":52},"let discount = 10\n\n\u002F\u002F finalPriceImpure :: Number -> Number\n\u002F\u002F IMpure: the result depends on the outer variable discount\nconst finalPriceImpure = (price) => price - price * discount \u002F 100\n\n\u002F\u002F finalPrice :: (Number, Number) -> Number\n\u002F\u002F your code\n\nconsole.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)\n\ndiscount = 50 \u002F\u002F someone changed the outer variable\n\nconsole.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)",{"ru":7,"en":54},"let discount = 10\n\n\u002F\u002F finalPriceImpure :: Number -> Number\n\u002F\u002F IMpure: the result depends on the outer variable discount\nconst finalPriceImpure = (price) => price - price * discount \u002F 100\n\n\u002F\u002F finalPrice :: (Number, Number) -> Number\n\u002F\u002F Pure: everything the result depends on comes in as arguments\nconst finalPrice = (percent, price) => price - price * percent \u002F 100\n\nconsole.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)\n\ndiscount = 50 \u002F\u002F someone changed the outer variable\n\nconsole.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)",{"ru":7,"en":56},"impure: 180, pure: 180\nimpure: 100, pure: 180",5,{"slug":59,"title":60},"closures",{"ru":7,"en":61},"Closures",{"slug":63,"title":64},"immutability",{"ru":7,"en":65},"Immutability",1792684724207]