Repository URL to install this package:
|
Version:
1.3.3 ▾
|
// @TODO good place to do logging
// @TODO return .find as a chain
import { equals } from 'ramda'
import forOwn from 'lodash/forOwn'
import {
isNil,
isPrimitive,
isFunction,
traverse,
where,
} from 'chain-able-boost'
const find = (specification, path, data) => {
let found = []
// turn primitive values into eq functions
forOwn(specification, (value, key) => {
if (isPrimitive(value)) {
specification[key] = equals(value)
}
})
traverse(data).forEach((key, x, traverser) => {
const isFound =
!isNil(x) && !found.includes(x) && isFunction(specification)
? specification(x)
: where(specification, x)
if (isFound) {
found.push(x)
// do not go any deeper
traverser.skip()
}
// console.log({ [key]: x, isFound })
})
return found
}
function finderMethod(this: any, specification, path) {
return this.findAll(specification, path)
}
// @TODO this would .stop() on first find
function findOne(this: any, specification, path) {
return this.find(specification, path)[0]
}
function findAll(this: any, specification, path) {
let data
if (isNil(path)) data = this.entries(true)
else data = this.get(path)
return find(specification, path, data)
}
export default find
export { finderMethod, findOne, findAll, find }