Skip to content

Instantly share code, notes, and snippets.

@collardeau
Last active November 10, 2015 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save collardeau/9f8c569a944866ca76d8 to your computer and use it in GitHub Desktop.
Save collardeau/9f8c569a944866ca76d8 to your computer and use it in GitHub Desktop.
Intro To FP Concepts, Part 3
// 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
<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