What's the best way to remove duplicates of an array of Either in Functional Programming using fp-ts
?
This is my attemp:
import { either as E, pipeable as P } from "fp-ts";
import { flow } from "fp-ts/lib/function";
interface IItem {
type: "VALID" | "INVALID";
value: string;
}
// Building some fake data
const buildItem = (value?: string): E.Either<unknown, string> =>
value != null ? E.right(value) : E.left({ type: "INVALID", value: "" });
// We will always have an array of Either
const items = [
buildItem("aa"),
buildItem("ab"),
buildItem(),
buildItem("ac"),
buildItem("ab"),
buildItem("ac"),
buildItem(),
buildItem("aa")
];
const checkList: string[] = [];
export const program = flow(
() => items,
x =>
x.reduce(
(acc, item) =>
P.pipe(
item,
E.chain(value => {
if (checkList.indexOf(value) < 0) {
checkList.push(value);
return E.right({ type: "VALID", value: value } as IItem);
}
return E.left({ type: "INVALID", value: value } as IItem);
}),
v => acc.concat(v)
),
[] as E.Either<unknown, IItem>[]
)
);