I'm venturing into trying to use functional programming in TypeScript, and am wondering about the most idiomatic way of doing the following using functional libraries such as ramda, remeda or lodash-fp. What I want to achieve is to apply a bunch of different functions to a specific data set and return the first truthy result. Ideally the rest of the functions wouldn't be run once a truthy result has been found, as some of those later in the list are quite computationally expensive. Here's one way of doing this 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
I mean, this function does the job, but is there a ready-made function in any of these libraries that would achieve the same result, or could I chain some of their existing functions together to do this? More than anything I'm just trying to get my head around functional programming and to get some advice on what would be an indiomatic approach to this problem.