[{"data":1,"prerenderedAt":70},["ShallowReactive",2],{"course-en-lenses":3},{"lesson":4,"number":61,"prev":62,"next":66},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":32,"exercises":42},"lenses",{"ru":7,"en":8},"","Lenses",{"ru":7,"en":10},"How JavaScript lenses read and update nested data without mutation: view, set and over from Ramda, and your own lens built from a getter and a setter.",{"ru":7,"en":12},"Learn to read and update nested data with lenses (view, set, over) without changing the original object, and understand how a simple lens built from a getter and a setter works.",[14,17,19,21,25,27,29],{"type":15,"ru":7,"en":16},"text","Lenses are a tool (a pattern) used in functional programming when working with data, providing data immutability and function purity.",{"type":15,"ru":7,"en":18},"Immutability means that data does not change after it is created: instead of modifying it, you create a new copy with the changes applied.",{"type":15,"ru":7,"en":20},"Let's take an example from the official documentation of the Ramda JS library.",{"type":22,"code":23},"code",{"ru":7,"en":24},"\u002F\u002F Lens s a = Functor f => (a -> f a) -> s -> f s\n\u002F\u002F ===============================\n\u002F\u002F create the lens\n\u002F\u002F the path to the data\nconst xHeadYLens = R.lensPath(['x', 0, 'y']);\n\n\u002F\u002F use the lens with different functions\n\n\u002F\u002F test data\nconst data = { x: [ { y: 2, z: 3 }, { y: 4, z: 5 } ] }\n\n\u002F\u002F view reads the data at the lens path\n\u002F\u002F without changing anything in the original object\nconst resultView = R.view(xHeadYLens, data);\n\n\u002F\u002F set writes new data\n\u002F\u002F at the lens path without changing the original object,\n\u002F\u002F returning a new object with the changed data instead\nconst resultSet = R.set(xHeadYLens, 1, data);\n\n\u002F\u002F over works with the lens like set,\n\u002F\u002F but instead of a value it takes a function\n\u002F\u002F that receives the data\n\u002F\u002F at the lens path as its argument\nconst resultOver = R.over(xHeadYLens, R.negate, data);\n\nconsole.log(resultView) \u002F\u002F 2\nconsole.log(resultSet) \u002F\u002F {x: [{y: 1, z: 3}, {y: 4, z: 5}]}\nconsole.log(resultOver) \u002F\u002F {x: [{y: -2, z: 3}, {y: 4, z: 5}]}",{"type":15,"ru":7,"en":26},"In the examples above, we saw how to use lenses.",{"type":15,"ru":7,"en":28},"And now let's try to implement our own custom lens. In production code, use ready-made solutions such as the lenses in Ramda JS (Sanctuary JS has no lenses).",{"type":22,"code":30},{"ru":7,"en":31},"\u002F\u002F a simplified lens: a pair of getter and setter functions\n\u002F\u002F closed over the path to the data\n\u002F\u002F Lens s a = { getter :: s -> a, setter :: (a | (a -> a)) -> s -> s }\n\u002F\u002F in Ramda a lens is encoded differently: Functor f => (a -> f a) -> s -> f s\n\u002F\u002F ===============================\n\u002F\u002F create the lens\n\u002F\u002F lens :: [String | Number] -> Lens s a\nconst lens = (path) => {\n\n  \u002F\u002F getter :: [String | Number] -> s -> a\n  const getter = (path) => (data) => {\n    \u002F\u002F if no path was passed to the lens,\n    \u002F\u002F return the data as is\n    if (!path.length) {\n      return data\n    }\n\n    \u002F\u002F the first path element and the rest of the path\n    const [head, ...tail] = path\n\n    \u002F\u002F when one element is left in the path,\n    \u002F\u002F there is no tail:\n    \u002F\u002F this is the base case,\n    \u002F\u002F and we return the data\n    if (!tail.length) {\n      return data[head]\n    }\n\n    \u002F\u002F recursive case\n    \u002F\u002F pass the shortened path as the first argument\n    \u002F\u002F and the nested value as the data\n    return getter (tail) (data[head])\n  }\n\n  \u002F\u002F a copy of the node with a new value under the key\n  \u002F\u002F an array is copied as an array: {...data} would turn it\n  \u002F\u002F into an object with keys 0, 1 and so on\n  \u002F\u002F assoc :: (String | Number) -> a -> s -> s\n  const assoc = (key) => (value) => (data) => {\n    const copy = Array.isArray(data) ? [...data] : { ...data }\n    copy[key] = value\n    return copy\n  }\n\n  \u002F\u002F setter :: [String | Number] -> (a | (a -> a)) -> s -> s\n  const setter = (path) => (v) => (data) => {\n    \u002F\u002F if no path was passed to the lens,\n    \u002F\u002F return the data as is\n    if (!path.length) {\n      return data\n    }\n\n    \u002F\u002F the first path element and the rest of the path\n    const [head, ...tail] = path\n\n    \u002F\u002F when one element is left in the path,\n    \u002F\u002F there is no tail:\n    \u002F\u002F this is the base case,\n    \u002F\u002F and we return the data\n    \u002F\u002F with the key's value replaced\n    if (!tail.length) {\n\n      \u002F\u002F a check to tell\n      \u002F\u002F whether we are called as over or as set,\n      \u002F\u002F that is, whether a function or a value\n      \u002F\u002F was passed as the argument\n      \u002F\u002F so set cannot store a function as a value here:\n      \u002F\u002F in Ramda set is built on top of over and has no such limitation\n      const isFunction = typeof v === 'function'\n\n      return assoc (head) (\n        isFunction\n          ? v (data[head])\n          : v\n      ) (data)\n    }\n\n    \u002F\u002F recursive case\n    \u002F\u002F pass the shortened path as the first argument,\n    \u002F\u002F keep the change argument the same\n    \u002F\u002F and pass the nested value as the data\n    return assoc (head) (setter (tail) (v) (data[head])) (data)\n  }\n\n\n  \u002F\u002F return the getter and the setter,\n  \u002F\u002F keeping the path to the data in the closure\n  return {\n    getter: getter (path),\n    setter: setter (path),\n  }\n}\n\n\u002F\u002F the lens is ready\n\u002F\u002F now we need view, set and over\n\n\u002F\u002F we simply call the lens getter\n\u002F\u002F and pass it the data to process\n\u002F\u002F view :: Lens s a -> s -> a\nconst view = (lens) => (data) => lens.getter (data)\n\n\u002F\u002F we simply call the lens setter\n\u002F\u002F and pass it the data to process\n\u002F\u002F set :: Lens s a -> a -> s -> s\nconst set = (lens) => (v) => (data) => lens.setter (v) (data)\n\n\u002F\u002F implemented the same way as set\n\u002F\u002F over :: Lens s a -> (a -> a) -> s -> s\nconst over = (lens) => (fn) => (data) => lens.setter (fn) (data)\n\n\u002F\u002F testing the code\n\u002F\u002F =============\n\u002F\u002F create the lens\nconst xLens = lens(['x', 0, 'y']);\n\n\u002F\u002F test data\nconst data = { x: [ { y: 2, z: 3 }, { y: 4, z: 5 } ] }\n\nconst resultView = view (xLens) (data)\nconst resultSet = set (xLens) (1) (data)\n\u002F\u002F ((a) => (b) => a + b) (3) creates a curried function\n\u002F\u002F that is called right away and returns\n\u002F\u002F (b) => 3 + b\nconst resultOver = over (xLens) ( ((a) => (b) => a + b) (3) ) (data)\n\nconsole.log(resultView) \u002F\u002F 2\nconsole.log(resultSet) \u002F\u002F {x: [{y: 1, z: 3}, {y: 4, z: 5}]}\nconsole.log(resultOver) \u002F\u002F {x: [{y: 5, z: 3}, {y: 4, z: 5}]}",[33,35,36,38,40],{"ru":7,"en":34},"Lenses are a pattern for working with data that keeps the data immutable and the functions pure.",{"ru":7,"en":18},{"ru":7,"en":37},"view reads the value at the lens path, set writes a new value and returns a new object, and over works like set but takes a function of the current value. The original data stays unchanged.",{"ru":7,"en":39},"A simple lens can be built from a pair of getter and setter functions closed over the path to the data; when a node is copied, an array has to be copied as an array.",{"ru":7,"en":41},"In production code, use ready-made lenses such as the ones in Ramda; Sanctuary has no lenses.",[43,52],{"task":44,"starter":46,"solution":48,"expected":50},{"ru":7,"en":45},"The application state holds the user's settings and a cart. Using R.lensPath, R.view, R.set and R.over, get a new state where the theme is dark and the quantity of the first item in the cart has gone up by one. Combine both changes into a single update function with pipe and make sure the original state has not changed.",{"ru":7,"en":47},"\u002F\u002F pipe comes from Ramda, as in the \"Currying\" lesson\nconst { pipe } = R\n\nconst state = {\n  user: { name: 'Anna', settings: { theme: 'light', fontSize: 14 } },\n  cart: [\n    { title: 'Book', qty: 1 },\n    { title: 'Pen', qty: 3 },\n  ],\n}\n\n\u002F\u002F your code: the paths to the theme and to the quantity of the first item\nconst themeLens = R.lensPath([])\nconst firstQtyLens = R.lensPath([])\n\n\u002F\u002F your code: both changes with pipe, R.set and R.over\n\u002F\u002F update :: Object -> Object\nconst update = (s) => s\n\nconst next = update(state)\n\nconsole.log('new: theme ' + R.view(themeLens, next) + ', quantity ' + R.view(firstQtyLens, next))\nconsole.log('original: theme ' + R.view(themeLens, state) + ', quantity ' + R.view(firstQtyLens, state))",{"ru":7,"en":49},"\u002F\u002F pipe comes from Ramda, as in the \"Currying\" lesson\nconst { pipe } = R\n\nconst state = {\n  user: { name: 'Anna', settings: { theme: 'light', fontSize: 14 } },\n  cart: [\n    { title: 'Book', qty: 1 },\n    { title: 'Pen', qty: 3 },\n  ],\n}\n\n\u002F\u002F a lens to the theme\nconst themeLens = R.lensPath(['user', 'settings', 'theme'])\n\u002F\u002F a lens to the quantity of the first item: a path can contain an array index\nconst firstQtyLens = R.lensPath(['cart', 0, 'qty'])\n\n\u002F\u002F update :: Object -> Object\n\u002F\u002F each step returns a new object and passes it to the next one\nconst update = pipe(\n  (s) => R.set(themeLens, 'dark', s),\n  (s) => R.over(firstQtyLens, (qty) => qty + 1, s),\n)\n\nconst next = update(state)\n\nconsole.log('new: theme ' + R.view(themeLens, next) + ', quantity ' + R.view(firstQtyLens, next))\nconsole.log('original: theme ' + R.view(themeLens, state) + ', quantity ' + R.view(firstQtyLens, state))",{"ru":7,"en":51},"new: theme dark, quantity 2\noriginal: theme light, quantity 1",{"task":53,"starter":55,"solution":57,"expected":59},{"ru":7,"en":54},"In the hand-written lens from the lesson, set cannot store a function as a value: the setter treats any function as a transformation. Write a lens lensKey(key) for a single object key whose setter always takes a function, plus view, over and set. Build set on top of over, as Ramda does, and check that a function is stored as a plain value and the original object does not change.",{"ru":7,"en":56},"\u002F\u002F Lens s a = { getter :: s -> a, setter :: (a -> a) -> s -> s }\n\u002F\u002F lensKey :: String -> Lens s a\nconst lensKey = (key) => ({\n  getter: (data) => data[key],\n  \u002F\u002F your code: setter returns a copy of data with fn (data[key]) under the key\n  setter: (fn) => (data) => data,\n})\n\n\u002F\u002F view :: Lens s a -> s -> a\nconst view = (lens) => (data) => lens.getter(data)\n\n\u002F\u002F over :: Lens s a -> (a -> a) -> s -> s\nconst over = (lens) => (fn) => (data) => data \u002F\u002F your code\n\n\u002F\u002F set :: Lens s a -> a -> s -> s\nconst set = (lens) => (v) => (data) => data \u002F\u002F your code: on top of over\n\nconst user = { name: 'Anna', greet: null }\nconst nameLens = lensKey('name')\nconst greetLens = lensKey('greet')\n\nconsole.log(view(nameLens)(set(nameLens)('Kate')(user)))\nconsole.log(typeof view(greetLens)(set(greetLens)((name) => 'Hello, ' + name)(user)))\nconsole.log(view(nameLens)(over(nameLens)((name) => name.toUpperCase())(user)))\nconsole.log(user)",{"ru":7,"en":58},"\u002F\u002F Lens s a = { getter :: s -> a, setter :: (a -> a) -> s -> s }\n\u002F\u002F lensKey :: String -> Lens s a\nconst lensKey = (key) => ({\n  getter: (data) => data[key],\n  \u002F\u002F the setter always takes a function and does not check what it got\n  setter: (fn) => (data) => {\n    const copy = { ...data }\n    copy[key] = fn(data[key])\n    return copy\n  },\n})\n\n\u002F\u002F view :: Lens s a -> s -> a\nconst view = (lens) => (data) => lens.getter(data)\n\n\u002F\u002F over :: Lens s a -> (a -> a) -> s -> s\nconst over = (lens) => (fn) => (data) => lens.setter(fn)(data)\n\n\u002F\u002F set :: Lens s a -> a -> s -> s\n\u002F\u002F wrap the value in a function that ignores the current value,\n\u002F\u002F so v can be a function too\nconst set = (lens) => (v) => over(lens)(() => v)\n\nconst user = { name: 'Anna', greet: null }\nconst nameLens = lensKey('name')\nconst greetLens = lensKey('greet')\n\nconsole.log(view(nameLens)(set(nameLens)('Kate')(user)))\nconsole.log(typeof view(greetLens)(set(greetLens)((name) => 'Hello, ' + name)(user)))\nconsole.log(view(nameLens)(over(nameLens)((name) => name.toUpperCase())(user)))\nconsole.log(user)",{"ru":7,"en":60},"Kate\nfunction\nANNA\n{\n  \"name\": \"Anna\",\n  \"greet\": null\n}",18,{"slug":63,"title":64},"transducers",{"ru":7,"en":65},"Transducers",{"slug":67,"title":68},"side-effects-in-composition-functions",{"ru":7,"en":69},"Side effects in function composition",1792684725063]