首页 > 解决方案 > 替换 fp-ts 中的数组元素

问题描述

我将如何在下面的数组中cat替换字符串?dog

我下面的示例是标准 js 和 fp-ts 的混合,很好奇 Array 模块中是否有可以解决这个问题的东西。

const animals = ['monkey','cat','lion']

const result = pipe(
    animals,
    A.findIndex((animal)=> animal === 'cat'),
    O.matchW(
      () => animals,
      (index) => //Looking for fp-ts solution here
    )
  )

//Expected Result: ['monkey','dog','lion']

标签: fp-ts

解决方案


我会用A.updateAt. 请注意,我还包装O.none了条件结果,因此它们两个条件都返回Option<string[]>

O.matchW(
  () => O.some(animals),
  (index) => A.updateAt(index, 'dog')(animals)
)

推荐阅读