Last active
November 10, 2015 11:25
-
-
Save collardeau/9f8c569a944866ca76d8 to your computer and use it in GitHub Desktop.
Intro To FP Concepts, Part 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// functor factory | |
const right = { | |
of: val => functor(right, val), | |
fmap: function(f){ | |
return right.of(f(this.val)); | |
} | |
} | |
const left = { | |
of: val => functor(left, val), | |
fmap: function(f) { return this; } | |
} | |
const maybe = { | |
of: val => functor(maybe, val), // new ! | |
fmap: function(fn) { | |
if(this.val === null) return maybe.of(null); | |
return maybe.of(fn(this.val)); // changed | |
} | |
} | |
const functor = (functorType, val) => { | |
return Object.assign( | |
Object.create(functorType), | |
{ val: val } | |
) | |
} | |
// fmap any functor ! | |
const map = R.curry((fn, functor) => functor.fmap(fn)); | |
// building blocks | |
const getWords = string => { | |
var words = string.split(" "); | |
if (words.length === 3) { | |
return right.of(words); | |
} else { | |
return left.of("Not valid string") | |
} | |
} | |
const getFirstName = words => words[1]; | |
const getFirstLetter = string => string[0]; | |
// composition | |
const firstInitial = map( | |
R.pipe(getWords, map(getFirstName), map(getFirstLetter)) | |
); | |
// try it - messy! | |
const user = maybe.of("Doc Emmett Brown"); | |
console.log(firstInitial(user).val.val); // "E" | |
const badUser = maybe.of("Doc Brown"); | |
console.log(firstInitial(badUser).val.val); // "Not valid string" | |
const noUser = maybe.of(null); | |
console.log(firstInitial(noUser).val); // null |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.18.0/ramda.min.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment