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