Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/allouis/functor
https://github.com/allouis/functor
Last synced: 24 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/allouis/functor
- Owner: allouis
- Created: 2015-03-25T14:34:04.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2015-06-23T12:07:36.000Z (over 9 years ago)
- Last Synced: 2024-10-05T22:45:54.384Z (about 1 month ago)
- Language: JavaScript
- Size: 145 KB
- Stars: 4
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# functor
## Usage
```javascript
var functor = require('functor');
var fmap = functor.fmap;// We can define fmap methods on predefined types using the functor function
// N.B. this does not affect any prototype chains or modify external objects
functor(Promise, function(fn, functor){
// functor here is the promise instance
return functor.then(fn);
});functor(Array, function(fn, functor){
return functor.map(fn);
});// fmap will also look for an fmap method on the object
function Nothing() {}
Nothing.prototype.fmap = function () { return Nothing() };function Just(val) {
this.val = val;
}
Just.prototype.fmap = function (fn) { return Maybe(fn(this.val)) }function Maybe(val) {
return val == null ? Nothing() : Just(val)
}function logName(obj) {
console.log(obj.name);
return obj;
}var somePromise = getUserFromServer();
// this will log out the name at some point;
fmap(logName, somePromise); // returns a new functor, of same type (Promise);var me = {name: 'fabien'}
// this will log out "fabien"
fmap(logName, Maybe(me)); // returns new functor (Just)var you;
// this doesn't log out anything, nor does it throw a cannot read property name of null
fmap(logName, Maybe(you)); // returns new functor (Nothing)```