基于条件的参数金额的功能调用

发布于 2025-02-13 05:53:10 字数 834 浏览 1 评论 0原文

我有一个称为“ func”的函数:

const otherFunc = (arg1, arg2) => {...}
const func = (condition1, condition2) => {
 condition1 || condition2 ? otherFunc(value, true) : otherFunc(false)
}

以前的方法有效,但是我想知道是否有一种方法可以避免使用两个不同的呼叫。我尝试过,但不是正确的语法:

const func = (condition1, condition2) => {
 otherFunc((condition1 || condition2) && ...[value, true])
}

edit: 这是链接if和elses的简单功能:

function is(value, done) {
  return {
    else: (v) => is(done ? value : v, done),
    if: (condition) => (done || condition ? is(value, true) : is(null)),
    get: value,
  };
}
const n = 50000;
console.log(
  is('small')
    .if(n < 1000) 
    .else('big')
    .if(n > 10000)
    .else('medium-big')
    .if(n > 5000)
    .else('medium-small').get,
);

I have a function called 'func':

const otherFunc = (arg1, arg2) => {...}
const func = (condition1, condition2) => {
 condition1 || condition2 ? otherFunc(value, true) : otherFunc(false)
}

The previous way works, but i'm wondering if is there is a way to avoid using two different calls to otherFunc. I tried this but is not correct syntax:

const func = (condition1, condition2) => {
 otherFunc((condition1 || condition2) && ...[value, true])
}

Edit:
It is a simple function to chain if and elses:

function is(value, done) {
  return {
    else: (v) => is(done ? value : v, done),
    if: (condition) => (done || condition ? is(value, true) : is(null)),
    get: value,
  };
}
const n = 50000;
console.log(
  is('small')
    .if(n < 1000) 
    .else('big')
    .if(n > 10000)
    .else('medium-big')
    .if(n > 5000)
    .else('medium-small').get,
);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

破晓 2025-02-20 05:53:10

如果您可以将参数放入数组中,则可以在数组之间交替以扩散到参数列表中。

otherFunc(
  ...((condition1 || condition2) ? [value, true] : [false])
);

也就是说,这不是很可读。我真的更喜欢

if (condition1 || condition2) {
  otherFunc(value, true);
} else {
  otherFunc(false);
}

良好的可维护代码不是打高尔夫球比赛 - 绝对可能干燥并不总是最好的方法。

If you can put the arguments into an array, you can then alternate between the arrays to spread into the argument list.

otherFunc(
  ...((condition1 || condition2) ? [value, true] : [false])
);

That said, it isn't very readable. I'd really prefer

if (condition1 || condition2) {
  otherFunc(value, true);
} else {
  otherFunc(false);
}

Good maintainable code isn't a golfing competition - being as DRY as absolutely possible isn't always the best approach.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文