crocks
Version:
A collection of well known Algebraic Datatypes for your utter enjoyment.
61 lines (46 loc) • 1.52 kB
JavaScript
/** @license ISC License (c) copyright 2019 original and current authors */
/** @author Ian Hofmann-Hicks (evilsoft) */
var curry = require('../core/curry')
var isArray = require('../core/isArray')
var isEmpty = require('../core/isEmpty')
var isInteger = require('../core/isInteger')
var isNil = require('../core/isNil')
var isPredOrFunc = require('../core/isPredOrFunc')
var isString = require('../core/isString')
var predOrFunc = require('../core/predOrFunc')
var err = function (name) { return (name + ": First argument must be an Array of non-empty Strings or Integers"); }
function fn(name) {
// pathSatisfies: [ (String | Integer) ] -> (a -> Boolean) -> b -> Boolean
// pathSatisfies: [ (String | Integer) ] -> Pred a -> b -> Boolean
function pathSatisfies(keys, pred, x) {
if(!isArray(keys)) {
throw new TypeError(err(name))
}
if(!isPredOrFunc(pred)) {
throw new TypeError(
(name + ": Second argument must be a Pred or predicate Function")
)
}
if(isNil(x)) {
return false
}
var target = x
for(var i = 0; i < keys.length; i++) {
var key = keys[i]
if(!(isString(key) && !isEmpty(key) || isInteger(key))) {
throw new TypeError(err(name))
}
if(isNil(target)) {
return false
}
target = target[key]
}
return !!predOrFunc(pred, target)
}
return curry(pathSatisfies)
}
var pathSatisfies =
fn('pathSatisfies')
pathSatisfies.origFn =
fn
module.exports = pathSatisfies