我正要学习使用函数式编程fp-ts
,我只是在问自己,将这样的东西“转换”为函数式范式的正确函数式方法是什么:
//OOP:
interface Item {
name: string;
}
class X {
private readonly items: { [s:string]: Item[] } = {};
add(i: Item): Item {
if(!this.items.hasOwnProperty(i.name))
this.items[i.name] = [];
if(this.items[i.name].indexOf(i) < 0)
this.items[i.name].push(i);
return i;
}
}
所以,我想我应该这样走:
import * as O from 'fp-ts/es6/Option';
import * as E from 'fp-ts/es6/Either';
// using interfaces from above
interface state {
items: { [s:string]: Item[] }
}
export const createState = (): State => ({ items: {} });
export const add = (s: State, i: Item) => pipe(
// using IO here?
E.fromPredicate(
() => s.hasOwnProperty(i.name),
() => []
)
)
// to use it:
import { createState, add } from './fx';
let state = createState();
// update
state = add(state, {name: 'foo'})
既然add()
操作涉及到状态的修改,应该依赖IO
? 如果add
返回一个新的状态对象,它是一个纯函数,所以它不需要使用IO?所以我在这里提出的问题可能有点宽泛,但是:这里推荐的技术/模式是什么?