【发布时间】:2021-04-09 03:45:35
【问题描述】:
我正在冒险尝试在 TypeScript 中使用函数式编程,并且想知道使用函数库(如 ramda、remeda 或 lodash-fp)执行以下操作的最惯用方式。我想要实现的是将一堆不同的函数应用于特定的数据集并返回第一个真实的结果。理想情况下,一旦找到真实结果,其余函数就不会运行,因为列表中后面的一些函数在计算上非常昂贵。这是在常规 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
我的意思是,这个函数可以完成这项工作,但是这些库中是否有现成的函数可以实现相同的结果,或者我可以将它们的一些现有函数链接在一起来做到这一点?最重要的是,我只是想了解函数式编程并就解决此问题的惯用方法获得一些建议。
【问题讨论】:
标签: javascript typescript functional-programming lodash ramda.js