如何使用fp-ts实现数组中指定元素的替换操作
实现方案
可以使用 fp-ts Array 模块提供的 updateAt 方法完成指定索引位置的元素替换,符合你现有代码逻辑的完整实现如下:
import { pipe } from 'fp-ts/function' import * as A from 'fp-ts/Array' import * as O from 'fp-ts/Option' const animals = ['monkey','cat','lion'] const result = pipe( animals, A.findIndex((animal)=> animal === 'cat'), O.matchW( () => animals, (index) => pipe( animals, A.updateAt(index, 'dog'), // 此处index已经通过findIndex校验存在,getOrElse仅做类型安全兜底 O.getOrElse(() => animals) ) ) ) // 输出结果: ['monkey','dog','lion']
如果你的需求是替换数组中所有值为cat的元素,可以直接使用更简洁的map方案,不需要提前查找索引:
const result = pipe( animals, A.map(animal => animal === 'cat' ? 'dog' : animal) )
两种方案的差异:
- 第一种方案仅替换第一个匹配到的
cat,和你原有代码逻辑一致 - 第二种方案会替换数组中所有等于
cat的元素,适合批量替换场景
内容的提问来源于stack exchange,提问作者Jonathan Southern
相关产品推荐
相关产品推荐

