Functors Exercise 3 Solution

In notebook:
FrontEndMasters Hardcore Functional
Created at:
2017-04-05
Updated:
2017-07-15
Tags:
Functional Programming JavaScript
  // Exercise 3
// ==========
// Use safeGet and _.head to find the first initial of the user
var safeGet = _.curry(function(x,o){ return Maybe(o[x]) })
var user = {id: 2, name: "Albert"}
console.log("--------Start exercise 3--------")

var ex3 = undefined;
// the solution
var ex3 = compose(map(_.head), safeGet('name'))

assertDeepEqual(Maybe('A'), ex3(user))
console.log("exercise 3...ok!")

Explanation

safeGet works like get but puts inside a Maybe in case the value does not exist. So the first expressin of safeGet('name') returns us a functor, then we map over it.

Adding Maybe will save you a lot long error messages. In the above example, _.head will not run if user.name does not exist.

Also, you cannot do map(safeGet('name')) because this is not a Maybe yet. When you call it with all the arguments, then it returns a Maybe. This is also why you have to compose it.

###About curry and compose

(my notes)

curry: you define a function that can take n number of arguments. You can call the curried function with less arguments and you can call it again and again until all the arguments it needs exist, then it will run the original function

compose: passes the result of the second function in the arguments to the first one.