[{"data":1,"prerenderedAt":87},["ShallowReactive",2],{"course-en-currying":3},{"lesson":4,"number":78,"prev":79,"next":83},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":50,"exercises":59},"currying",{"ru":7,"en":8},"","Currying",{"ru":7,"en":10},"How a curried JavaScript function waits for all of its arguments, how to curry by hand and with curry, use it in composition and build specialized functions.",{"ru":7,"en":12},"Understand how a curried function postpones evaluation until it has all of its arguments, and learn to curry functions by hand and with curry to use them in composition and build specialized functions.",[14,17,19,27,31,33,35,38,40,43,45,47],{"type":15,"ru":7,"en":16},"text","Currying is one of the techniques used in functional programming, in which the function is evaluated only once all of its arguments have been supplied, while given only some of the arguments the function returns a new function.",{"type":15,"ru":7,"en":18},"Currying can be used:",{"type":20,"ordered":21,"items":22},"list",true,[23,25],{"ru":7,"en":24},"In function composition, when a function in a chain of calls expects two or more arguments.",{"ru":7,"en":26},"When we want to create specialized functions based on a base function by changing the value of an argument captured in a closure.",{"type":28,"code":29},"code",{"ru":7,"en":30},"\u002F\u002F  Example\n\u002F\u002F Currying\n\u002F\u002F sum :: Number -> Number -> Number -> Number\nconst sum  = (a) => (b) => (c) => a + b + c\n\n\u002F\u002F the function is evaluated only once it has all its arguments,\n\u002F\u002F otherwise it returns a new function\nconst result = sum (1) (2) (1)\n\nconsole.log(result) \u002F\u002F 4\n\n\u002F\u002F Partial calls of a curried function\n\n\u002F\u002F add :: Number -> Number -> Number\nconst add = (a) => (b) => a + b\n\n\u002F\u002F 10 is kept in the closure, waiting for the second argument;\n\u002F\u002F a function is returned\nconst add10 = add(10)\n\u002F\u002F once the second argument arrives,\n\u002F\u002F the function is fully evaluated\nconst resultAdded = add10(5) \u002F\u002F 15",{"type":15,"ru":7,"en":32},"So how do we curry an arbitrary function with n parameters whose values we don't know — for example, a function with 5 or more parameters?",{"type":15,"ru":7,"en":34},"We can automatically curry any function with a fixed number of parameters and pass it the arguments in any grouping: one at a time or several per call. Only the grouping changes; the order of the arguments stays the same.",{"type":28,"code":36},{"ru":7,"en":37},"\u002F\u002F Say we want to curry the sum function\n\u002F\u002F sum :: (Number, Number, Number) -> Number\nconst sum  = (a, b, c) => a + b + c\n\n\u002F\u002F a function that curries any function\n\u002F\u002F curry :: (* -> a) -> (* -> a)\nconst curry = (fn) => {\n  \u002F\u002F number of parameters of the function\n  const lengthFn = fn.length\n\n  \u002F\u002F inner function that will be called recursively\n  const curried = (...argsFirst) => {\n    \u002F\u002F if the number of incoming arguments is greater than or equal to\n    \u002F\u002F the number of the function's parameters, call it right away\n    if (argsFirst.length >= lengthFn) {\n      return fn(...argsFirst)\n    }\n\n    \u002F\u002F if there are fewer incoming arguments than the function\n    \u002F\u002F has parameters, return a new function\n    \u002F\u002F that collects the remaining arguments\n    return (...argsSecond) => curried(...argsFirst, ...argsSecond)\n  }\n\n  return curried\n}\n\n\u002F\u002F curry our sum function\nconst sumCurry = curry(sum)\n\n\u002F\u002F now the arguments can be passed in any grouping\nconsole.log( sumCurry (1) (1) (1) ) \u002F\u002F 3\nconsole.log( sumCurry (1, 1) (1) ) \u002F\u002F 3\nconsole.log( sumCurry (1) (1, 1) ) \u002F\u002F 3\nconsole.log( sumCurry (1, 1, 1) ) \u002F\u002F 3",{"type":15,"ru":7,"en":39},"Now let's look at the full power of currying through examples of function composition.",{"type":28,"code":41},{"ru":7,"en":42},"\u002F\u002F For example, the following composition will\n\u002F\u002F =====================================\n\u002F\u002F use two curried functions:\n\u002F\u002F one is curried in advance,\n\u002F\u002F and the other we curry automatically before calling it\n\n\u002F\u002F pipe and curry come from Ramda: the course playground exposes it as R\nconst { pipe, curry } = R\n\n\u002F\u002F the data we will work with:\n\u002F\u002F a list of users\n\u002F\u002F fetchAllUsers :: () -> Promise [Object]\nconst fetchAllUsers = () => new Promise(resolve => resolve([\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 Our task\n\u002F\u002F 1. Get the users whose status is online\n\u002F\u002F 2. Who are older than 30\n\u002F\u002F 3. Take their names\n\n\u002F\u002F filter :: (a -> Boolean) -> [a] -> [a]\nconst filter = (fn) => (arr) => arr.filter(fn)\n\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst map = (fn) => (arr) => arr.map(fn)\n\n\u002F\u002F a predicate function that checks the status\n\u002F\u002F isStatus :: String -> String -> a -> Boolean\nconst isStatus = (status) => (prop) => (user) => user[prop] === status\n\n\u002F\u002F isMoreAge :: (Number, String, a) -> Boolean\nconst isMoreAge = (age, prop, user) => user[prop] > age\n\n\u002F\u002F let's auto-curry the function above\nconst isMoreAgeCurry = curry(isMoreAge)\n\n\u002F\u002F call it twice and create an abstraction with a clear name:\n\u002F\u002F a predicate function that checks the age\nconst isMoreAge30 = isMoreAgeCurry (30) ('age')\n\n\u002F\u002F get a value by key\n\u002F\u002F getByProp :: String -> a -> String\nconst getByProp = (prop) => (user) => user[prop]\n\n\u002F\u002F  keep the key 'name' in the closure and wait for an object\n\u002F\u002F getName :: a -> String\nconst getName = getByProp('name')\n\n\u002F\u002F prepare the composition; on the next call\n\u002F\u002F it expects an array of users as the argument\nconst pipeline = pipe (\n  filter ( isStatus ('online') ('status') ), \u002F\u002F keep only online users\n  filter ( isMoreAge30 ), \u002F\u002F older than 30\n  map ( getName ), \u002F\u002F return the names\n)\n\nconst showAdultsUsers = async () => {\n\n  \u002F\u002F run the promise with the data,\n  \u002F\u002F pass the data into the composition and run it\n  const adultsUsers = await fetchAllUsers()\n                                          .then(pipeline)\n\n  console.log(adultsUsers) \u002F\u002F ['Angel']\n}\n\nshowAdultsUsers()\n\n\n\u002F\u002F =============================\n\n\u002F\u002F the code above reads nicely,\n\u002F\u002F but if there are tens of thousands of users\n\u002F\u002F and we need to optimize, we can avoid\n\u002F\u002F traversing the array twice with filter\nconst pipelineOnePass = pipe (\n  filter (\n    (user) => (\n      isStatus ('online') ('status') (user) && isMoreAge30 (user)\n    )\n  ), \u002F\u002F a single pass checking both predicates at once\n  map ( getName ), \u002F\u002F return the names\n)",{"type":15,"ru":7,"en":44},"We can also create specialized functions with the help of currying. It is somewhat similar to \"inheritance\" in OOP.",{"type":15,"ru":7,"en":46},"We take a base curried function, and then we build other functions through calls. Enough theory — let's get straight to the examples.",{"type":28,"code":48},{"ru":7,"en":49},"\u002F\u002F Let's take a curried function\n\u002F\u002F and start building other specialized functions from it\n\n\u002F\u002F Base function that compares the value under a given key\n\u002F\u002F equalBy :: String -> * -> a -> Boolean\nconst equalBy = (prop) => (value) => (obj) => obj[prop] === value\n\n\u002F\u002F the data we will work with\nconst user = { name: 'John', status: 'online', married: true }\n\n\u002F\u002F we could call the function all at once\nconst onlineStatusUser = equalBy ('status') ('online') (user)\n\n\u002F\u002F check whether the user's status is online\nconsole.log(onlineStatusUser) \u002F\u002F true\n\n\u002F\u002F now let's start building\n\u002F\u002F specialized functions from equalBy\n\n\u002F\u002F compare by the status key\nconst equalByStatus = equalBy ('status')\n\u002F\u002F compare by the married key\nconst equalByMarried = equalBy ('married')\n\n\u002F\u002F add one more layer of abstraction\n\u002F\u002F is online\nconst isOnline = equalByStatus ('online')\n\u002F\u002F is offline\nconst isOffline = equalByStatus ('offline')\n\n\u002F\u002F is married\nconst isMarried = equalByMarried (true)\n\u002F\u002F is not married\nconst isNotMarried = equalByMarried (false)\n\n\u002F\u002F we can write a negation helper\n\u002F\u002F for the last functions\n\u002F\u002F not :: (a -> Boolean) -> a -> Boolean\nconst not = (fn) => (...args) => !fn(...args)\n\n\u002F\u002F a human-readable \"not online\" expression\nconst offlineUserCheck = not (isOnline)\nconst notMarriedCheck = not (isMarried)\n\n\u002F\u002F now let's run our specialized functions\n\u002F\u002F and check whether the user is online and married\n\n\u002F\u002F get the user's status\nconst isOnlineUser = isOnline (user)\n\u002F\u002F  check whether the user is married\nconst isMarriedUser = isMarried (user)\n\n\u002F\u002F now let's only let users who are married and online\n\u002F\u002F into our app\n\n\u002F\u002F write a helper\n\u002F\u002F and :: Boolean -> Boolean -> Boolean\nconst and = (valueFirst) => (valueSecond) => valueFirst && valueSecond\n\n\u002F\u002F note that the code has become human-readable\n\u002F\u002F and highly abstract:\n\u002F\u002F each function does one logical operation,\n\u002F\u002F the code says what it does, not how\nif (and (isOnlineUser) (isMarriedUser) ) {\n  \u002F\u002F do something here ...\n}",[51,53,55,57],{"ru":7,"en":52},"A curried function is evaluated only once it has all of its arguments; given only some of them, it returns a new function.",{"ru":7,"en":54},"Currying is used in function composition, when a function in a chain of calls expects two or more arguments, and to create specialized functions based on a base function.",{"ru":7,"en":56},"Any function with a fixed number of parameters can be curried automatically and given its arguments in any grouping: only the grouping changes, the order of the arguments stays the same.",{"ru":7,"en":58},"Specialized functions are built from a base curried function through calls: equalByStatus from equalBy, then isOnline from equalByStatus. This is somewhat similar to \"inheritance\" in OOP.",[60,69],{"task":61,"starter":63,"solution":65,"expected":67},{"ru":7,"en":62},"Write a curried function formatLog :: String -> String -> String -> String by hand: it takes a level, a module name and a message and returns a string like [ERROR] auth: wrong password. Build specialized functions from it: logError and logInfo with the level fixed, and from those, authError and cartInfo with the module fixed. Use them to print the messages from the starter.",{"ru":7,"en":64},"\u002F\u002F formatLog :: String -> String -> String -> String\n\u002F\u002F your code\n\nconsole.log(authError('wrong password'))\nconsole.log(authError('token expired'))\nconsole.log(cartInfo('item added'))",{"ru":7,"en":66},"\u002F\u002F formatLog :: String -> String -> String -> String\nconst formatLog = (level) => (moduleName) => (message) => `[${level}] ${moduleName}: ${message}`\n\n\u002F\u002F the level is kept in the closure, the function waits for the module\nconst logError = formatLog('ERROR')\nconst logInfo = formatLog('INFO')\n\n\u002F\u002F the level and the module are kept, the function waits only for the message\nconst authError = logError('auth')\nconst cartInfo = logInfo('cart')\n\nconsole.log(authError('wrong password'))\nconsole.log(authError('token expired'))\nconsole.log(cartInfo('item added'))",{"ru":7,"en":68},"[ERROR] auth: wrong password\n[ERROR] auth: token expired\n[INFO] cart: item added",{"task":70,"starter":72,"solution":74,"expected":76},{"ru":7,"en":71},"applyDiscount(percent, price) expects two arguments, while map hands the function one price at a time. Curry it with curry from Ramda, fix a 10% discount and use pipe to build totalWithDiscount: it takes the prices of the order items, applies the discount to each of them and adds them up.",{"ru":7,"en":73},"\u002F\u002F pipe and curry come from Ramda\nconst { pipe, curry } = R\n\nconst order = [\n  { title: 'Book', price: 400 },\n  { title: 'Pen', price: 50 },\n  { title: 'Lamp', price: 1200 },\n]\n\n\u002F\u002F applyDiscount :: (Number, Number) -> Number\nconst applyDiscount = (percent, price) => price - (price * percent) \u002F 100\n\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst map = (fn) => (arr) => arr.map(fn)\n\u002F\u002F getByProp :: String -> a -> b\nconst getByProp = (prop) => (obj) => obj[prop]\n\u002F\u002F sum :: [Number] -> Number\nconst sum = (arr) => arr.reduce((acc, n) => acc + n, 0)\n\n\u002F\u002F your code\n\nconsole.log(totalWithDiscount(order))",{"ru":7,"en":75},"\u002F\u002F pipe and curry come from Ramda\nconst { pipe, curry } = R\n\nconst order = [\n  { title: 'Book', price: 400 },\n  { title: 'Pen', price: 50 },\n  { title: 'Lamp', price: 1200 },\n]\n\n\u002F\u002F applyDiscount :: (Number, Number) -> Number\nconst applyDiscount = (percent, price) => price - (price * percent) \u002F 100\n\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst map = (fn) => (arr) => arr.map(fn)\n\u002F\u002F getByProp :: String -> a -> b\nconst getByProp = (prop) => (obj) => obj[prop]\n\u002F\u002F sum :: [Number] -> Number\nconst sum = (arr) => arr.reduce((acc, n) => acc + n, 0)\n\n\u002F\u002F the 10% discount is kept in the closure, the function waits for a price\n\u002F\u002F discount10 :: Number -> Number\nconst discount10 = curry(applyDiscount)(10)\n\n\u002F\u002F totalWithDiscount :: [Object] -> Number\nconst totalWithDiscount = pipe(\n  map(getByProp('price')), \u002F\u002F item prices\n  map(discount10), \u002F\u002F discount on each price\n  sum, \u002F\u002F total\n)\n\n\u002F\u002F 360 + 45 + 1080\nconsole.log(totalWithDiscount(order))",{"ru":7,"en":77},"1485",9,{"slug":80,"title":81},"composition",{"ru":7,"en":82},"Function composition",{"slug":84,"title":85},"partial-application",{"ru":7,"en":86},"Partial application",1792684724207]