As I delve into the world of functional programming in TypeScript, I find myself contemplating the most idiomatic way to achieve a specific task using libraries like ramda, remeda, or lodash-fp. My goal is to apply a series of functions to a particular dataset and return the first truthy result. Ideally, I would like to avoid running the remaining functions once a truthy result is found, especially considering that some of the later functions can be quite computationally expensive. Here's an example of how this can be done in regular ES6:
const firstTruthy = (functions, data) => {
let result = null
for (let i = 0; i < functions.length; i++) {
res = functions[i](data)
if (res) {
result = res
break
}
}
return result
}
const functions = [
(input) => input % 3 === 0 ? 'multiple of 3' : false,
(input) => input * 2 === 8 ? 'times 2 equals 8' : false,
(input) => input + 2 === 10 ? 'two less than 10' : false
]
firstTruthy(functions, 3) // 'multiple of 3'
firstTruthy(functions, 4) // 'times 2 equals 8'
firstTruthy(functions, 8) // 'two less than 10'
firstTruthy(functions, 10) // null
Although this function gets the job done, I wonder if there is a pre-existing function in any of these libraries that could achieve the same result, or if I could chain together some of their existing functions to accomplish this. My main goal is to grasp functional programming concepts and seek advice on the most idiomatic approach to solving this problem.