Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const Future = require('fluture');
const R = require('ramda');
const Reader = require('./monads/reader');
// Setup
const FakeDb = () => {
const data = {
1: {id: 1, name: 'bob', bff: 2},
2: {id: 2, name: 'alice', bff: 1}
};
const byId = id => Future.of(data[id]);
const save = (id, value) => {
data[id] = value;
return Future.of(value);
};
return { byId, save };
};
const upperName = data => data.name.toUpperCase();
const raw = () => {
const program = Reader(db => db.byId(1))
.chain(future => {
return Reader(config => {
return future.chain(data => {
return Reader(db => db.byId(data.bff)).run(config);
});
});
})
.map(responseFuture => responseFuture.map(upperName));
program.run(FakeDb()).value(console.log);
}
const monadTransformer = () => {
const ReaderT = value => {
const map = fn => ReaderT(value.map(future => future.map(fn)));
const chain = fn => ReaderT(value.chain(future => {
return Reader(req => {
return future.chain((...args) => {
return fn(...args).run(req);
});
});
}));
return Object.freeze({ map, chain, run: value.run });
}
const program = ReaderT(Reader(db => db.byId(1)))
.chain(data => ReaderT(Reader(db => db.byId(data.bff))))
.map(upperName)
program.run(FakeDb()).value(console.log);
}
raw();
monadTransformer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment