我有这个功能,有两个if
s 我想根据我收到的字母数字代码找到用户。我如何用sanctuary-js重构这个?
//const code = '0011223344';
const code = 'aabbc';
const isNumberCode = code => !!/^[0-9]{10}$/.exec(code);
const isLiteralCode = code => !!/^[A-Za-z]{5}$/.exec(code);
const findUser = (criteria) => {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('user object');
}, 300);
});
}
async function handler(code) {
if (isNumberCode(code)) {
const user = await findUser({id: code});
return user;
}
if (isLiteralCode(code)) {
const user = await findUser({identifier: code});
return user;
}
return 'not found';
}
async function run() {
const user = await handler(code);
console.log(user)
}
run();
我不明白我应该如何处理三种不同的类型:数字代码、文字代码和未找到代码。
- 更新
这是我的功能解决方案(我可能这么认为):
const Code = x => ({
chain: f => f(x),
fold: (e, a, f) => e(x)
});
const ErrorCode = x => ({
fold: (e, a, f) => e(x),
findLabel: f => ErrorCode(x)
});
const PromiseToCode = promise => ({
fold: (e, a, f) => promise.then(x => x.fold(e, a, f))
});
const NumberCode = x => ({
fold: (e, a, f) => a(x),
findLabel: f => PromiseToCode(f(x, {activationCode: x}, NumberCode))
});
const LiteralCode = x => ({
fold: (e, a, f) => f(x),
findLabel: f => PromiseToCode(f(x, {finderCode: x}, LiteralCode))
});
const checkTypeOfCode = code => {
if (isNumberCode(code)) {
return NumberCode(code);
}
if (isLiteralCode(code)) {
return LiteralCode(code);
}
return ErrorCode(code);
};
const find = async (code, criteria, type) => {
const user = findUser();
if (!user) {
return ErrorCode(code);
}
return type(user);
};
const handler2 = (code) =>
Code(code)
.chain(checkTypeOfCode)
.findLabel(find)
.fold(
e => 'not found',
a => 'user object find by id',
l => 'user object find by identifier'
)
handler2(code).then(console.log);
但我不知道它是否是好的代码。另外我问的是 sanctuary-js,因为我认为所有这些对象都不是编程的好方法。