rubico
Version:
[a]synchronous functional programming
90 lines (76 loc) • 2.14 kB
JavaScript
/**
* rubico v2.6.2
* https://github.com/a-synchronous/rubico
* (c) 2019-2024 Richard Tong
* rubico may be freely distributed under the MIT license.
*/
const isArray = Array.isArray
const isPromise = value => value != null && typeof value.then == 'function'
const thunkConditional = (
conditionalExpression, thunkOnTruthy, thunkOnFalsy,
) => conditionalExpression ? thunkOnTruthy() : thunkOnFalsy()
const __ = Symbol.for('placeholder')
const always = value => function getter() { return value }
// argument resolver for curry3
const curry3ResolveArg0 = (
baseFunc, arg1, arg2,
) => function arg0Resolver(arg0) {
return baseFunc(arg0, arg1, arg2)
}
// argument resolver for curry3
const curry3ResolveArg1 = (
baseFunc, arg0, arg2,
) => function arg1Resolver(arg1) {
return baseFunc(arg0, arg1, arg2)
}
// argument resolver for curry3
const curry3ResolveArg2 = (
baseFunc, arg0, arg1,
) => function arg2Resolver(arg2) {
return baseFunc(arg0, arg1, arg2)
}
const curry3 = function (baseFunc, arg0, arg1, arg2) {
if (arg0 == __) {
return curry3ResolveArg0(baseFunc, arg1, arg2)
}
if (arg1 == __) {
return curry3ResolveArg1(baseFunc, arg0, arg2)
}
return curry3ResolveArg2(baseFunc, arg0, arg1)
}
const thunkify3 = (func, arg0, arg1, arg2) => function thunk() {
return func(arg0, arg1, arg2)
}
const findIndexAsync = async function (predicate, array, index) {
const length = array.length
while (++index < length) {
let predication = predicate(array[index])
if (isPromise(predication)) {
predication = await predication
}
if (predication) {
return index
}
}
return -1
}
const findIndex = predicate => function findingIndex(array) {
const length = array.length
let index = -1
while (++index < length) {
const predication = predicate(array[index])
if (isPromise(predication)) {
return predication.then(curry3(
thunkConditional,
__,
always(index),
thunkify3(findIndexAsync, predicate, array, index),
))
}
if (predication) {
return index
}
}
return -1
}
export default findIndex