crocks
Version:
A collection of well known Algebraic Datatypes for your utter enjoyment.
34 lines (24 loc) • 1.1 kB
JavaScript
/** @license ISC License (c) copyright 2018 original and current authors */
/** @author Dale Francis (dalefrancis88) */
var Pred = require('../core/types').proxy('Pred')
var curry = require('../core/curry')
var predOrFunc = require('../core/predOrFunc')
var isFunction = require('../core/isFunction')
var isFoldable = require('../core/isFoldable')
var isSameType = require('../core/isSameType')
var ref = require('.');
var Just = ref.Just;
var Nothing = ref.Nothing;
var accumulator = function (fn) { return function (acc, cur) { return !acc.found && predOrFunc(fn, cur) ? { found: true, value: cur } : acc; }; }
// find :: Foldable f => ((a -> Boolean) | Pred) -> f a -> Maybe a
function find(fn, foldable) {
if(!isFunction(fn) && !isSameType(Pred, fn)) {
throw new TypeError('find: First argument must be a Pred or predicate')
}
if(!isFoldable(foldable)) {
throw new TypeError('find: Second argument must be a Foldable')
}
var result = foldable.reduce(accumulator(fn), { found: false })
return result.found ? Just(result.value) : Nothing()
}
module.exports = curry(find)