Either/IO Exercise 2,3 and 4
Exercise 2
// Exercise 2
// ==========
// Write a validation function that checks for a length > 3. It should return Right(x) if it is greater than 3 and Left("You need > 3") otherwise
console.log("--------Start exercise 2--------")
var ex2 = function(x) {
// return "TODO: write me";
// **** 1. the solution:
return (x.length > 3) ? Right(x) : Left("You need > 3")
}
assertDeepEqual(Right("fpguy99"), ex2("fpguy99"))
assertDeepEqual(Left("You need > 3"), ex2("..."))
Above: we just wrote a validation that returns a Right
or a Left
// Exercise 3
// ==========
// Use ex2 above and Either as a functor to save the user if they are valid
var save = function(x){ console.log("SAVED USER!"); return x; }
var ex3 = undefined
// solution
var ex3 = compose(map(save), ex2)
console.log("--------Start exercise 2--------")
assertDeepEqual(Right("fpguy99"), ex3("fpguy99"))
assertDeepEqual(Left("You need > 3"), ex3("duh"))
// Exercise 4
// ==========
// Get the text from the input and strip the spaces
console.log("--------Start exercise 4--------")
var getValue = function(x){ return document.querySelector(x).value }.toIO()
var stripSpaces = function(s){ return s.replace(/\s+/g, ''); }
var ex4 = undefined
// solution
var ex4 = compose(map(stripSpaces), getValue)
assertEqual("honkeytonk", runIO(ex4('#text')))
What's great is that map
is so generic that you can put in any type of container.
This exercise uses IO
. Note the in assertEqual
you have to run it with runIO(ex4('#text'))
because it has an IO
in it.