有没有办法缩短这段代码?
const result = getResult();
if (!result) {
return;
}
// Work with result
我的代码中一直有很多这样的东西,我很乐意做这样的事情:
const result = getResult() || return;
// Work with result
编辑: 我只希望保留可转换输入。
const parseInput = (input: string): void => {
const convertedInput = convert(input);
if (!convertedInput) {
return;
}
persist(convertedInput);
}
我知道我可以调用转换器两次。但我想避免这种情况:
const parseInput = (input: string): void => {
if (!convert(input)) {
return;
}
persist(convert(input));
}
最佳答案
你的代码已经很好了,但是,如果你想尝试一下函数式风格,你可以将值包装到“monad”中,只有当值不为零时它才会调用附加函数.这是一个玩具实现:
function maybe(x) {
return {
value: x,
apply(fn) {
if (this.value)
this.value = fn(this.value)
return this;
}
}
}
有了这个也许
,你的例子看起来像:
const parseInput = input => maybe(convert(input)).apply(persist)
参见 Oliver's answer更严肃的方法。
关于JavaScript:如果函数返回 null,则快速返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683524/