crocks
Version:
A collection of well known Algebraic Datatypes for your utter enjoyment.
41 lines (30 loc) • 1.16 kB
JavaScript
/** @license ISC License (c) copyright 2017 original and current authors */
/** @author Ian Hofmann-Hicks (evil) */
var Either = require('.')
var First = require('../core/types').proxy('First')
var curry = require('../core/curry')
var isFunction = require('../core/isFunction')
var isSameType = require('../core/isSameType')
var constant = function (x) { return function () { return x; }; }
var applyTransform = function (left, first) { return first.valueOf().either(
constant(Either.Left(left)),
Either.Right
); }
// firstToEither : c -> First a -> Either c a
// firstToEither : c -> (a -> First b) -> a -> Either c b
function firstToEither(left, first) {
if(isFunction(first)) {
return function(x) {
var m = first(x)
if(!isSameType(First, m)) {
throw new TypeError('firstToEither: First returning function required for second argument')
}
return applyTransform(left, m)
}
}
if(isSameType(First, first)) {
return applyTransform(left, first)
}
throw new TypeError('firstToEither: First or First returning function required for second argument')
}
module.exports = curry(firstToEither)