moy-fp
Version:
A functional programming library.
64 lines (61 loc) • 1.28 kB
JavaScript
/**
* Task is a Functor, Monad and Applicative
* can map
* can join
* can chain
* can ap
* always use for asynchronous task and side effects
* can also handle synchronous task if you'd like
* a super Functor, can't convert to other Functor, but other Functor can easy convert to Task
* you may not need it if you are not sensitive in functional programming
*/
const Task = fork => Object.seal(
Object.create(null, {
fork: {
value: fork,
},
[Symbol.toStringTag]: {
value: 'Task',
},
map: {
value: function map(fn){
return Task(
(reject, resolve) => this.fork(
reject,
x => resolve(fn(x))
)
)
},
},
join: {
value: function join(){
return this.chain(x => x)
},
},
chain: {
value: function chain(fn){
return Task(
(reject, resolve) => this.fork(
reject,
x => fn(x).fork(
reject,
resolve,
)
)
)
},
},
ap: {
value: function ap(T){
return this.chain(fn => T.map(fn))
},
},
})
)
/**
* Functor Task => a -> Task a
*/
Task.of = x => Task(
(_, resolve) => resolve(x)
)
export default Task