crocks
Version:
A collection of well known Algebraic Datatypes for your utter enjoyment.
48 lines (34 loc) • 963 B
JavaScript
/** @license ISC License (c) copyright 2017 original and current authors */
/** @author Ian Hofmann-Hicks (evil) */
var isFunction = require('../core/isFunction')
var isPromise = require('../core/isPromise')
var err = 'pipeP: Promise returning functions required'
function applyPipe(f, g) {
if(!isFunction(g)) {
throw new TypeError(err)
}
return function() {
var p = f.apply(null, arguments)
if(!isPromise(p)) {
throw new TypeError(err)
}
return p.then(g)
}
}
// pipeP : Promise p => ((a -> p b), (b -> p c), ..., (y -> p z)) -> a -> p z
function pipeP() {
var fns = [], len = arguments.length;
while ( len-- ) fns[ len ] = arguments[ len ];
if(!arguments.length) {
throw new TypeError(err)
}
var head =
fns[0]
if(!isFunction(head)) {
throw new TypeError(err)
}
var tail =
fns.slice(1).concat(function (x) { return x; })
return tail.reduce(applyPipe, head)
}
module.exports = pipeP