Both Haskell and PureScript languages provide syntactic sugar for working with monads in the form of do notation.
- 출처) FP-TS 문서
type userInput = {
email: string;
age: number;
name: string;
};
const combinedFunction = (data: userInput) => {
// 각 data 를 받아서 처리 function 의 집합
return '';
};
export const validateUserInput = (data: userInput) => {
return pipe(data, combinedFunction);
};
it('normal case: not using do', () => {
const data = { email: 'email', age: 30, name: 'name' };
const res = validateUserInput(data);
expect(res).not.toBeNull();
});
import * as E from 'fp-ts/Either';
import { pipe } from 'fp-ts/lib/function';
const validateEmail = (email: string) => {
return email.includes('@') ? E.right(email) : E.left('wrong email');
};
const validateAge = (age: number) => {
return age >= 20 ? E.right(age) : E.left('wrong age');
};
const validateName = (name: string) => {
return name !== '' ? E.right(name) : E.left('wrong name');
};
type userInput = {
email: string;
age: number;
name: string;
};
export const validateUserInfo = (data: userInput) => {
return pipe(data, ({ email, age, name }) => {
return pipe(
E.Do,
E.bind('vEmail', () => validateEmail(email)),
E.bind('vAge', () => validateAge(age)),
E.bind('vName', () => validateName(name)),
E.map(({ vEmail, vAge, vName }) => {
return { vEmail, vAge, vName };
})
);
});
};
export const validateUserInfoTwo = (data: userInput) => {
return pipe(
E.Do,
E.bind('vEmail', () => validateEmail(data.email)),
E.bind('vAge', () => validateAge(data.age)),
E.bind('vName', () => validateName(data.name)),
E.map(({ vEmail, vAge, vName }) => {
return { vEmail, vAge, vName };
})
);
};