最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Conditional operator for an operator - Stack Overflow

programmeradmin1浏览0评论

I have a piece of code:

if (foo > bar) {
    baz = foo - bar
} else {
    baz = foo + bar
}

I have a question if I can somehow shorten this code to a single line, something like

PSEUDOCODE:

baz = foo (foo > bar ? + : -) bar

Real code I'd like to shorten

if (gradientStartH > gradientEndH) {
    h = gradientStartH - Math.abs(gradientStartH - gradientEndH) / arr.length * i
} else {
    h = gradientStartH + Math.abs(gradientStartH - gradientEndH) / arr.length * i
}

Thanks!

I have a piece of code:

if (foo > bar) {
    baz = foo - bar
} else {
    baz = foo + bar
}

I have a question if I can somehow shorten this code to a single line, something like

PSEUDOCODE:

baz = foo (foo > bar ? + : -) bar

Real code I'd like to shorten

if (gradientStartH > gradientEndH) {
    h = gradientStartH - Math.abs(gradientStartH - gradientEndH) / arr.length * i
} else {
    h = gradientStartH + Math.abs(gradientStartH - gradientEndH) / arr.length * i
}

Thanks!

Share Improve this question edited Mar 8, 2019 at 20:17 Pavel T asked Mar 8, 2019 at 19:24 Pavel TPavel T 976 bronze badges 3
  • 3 If the operation is "much more plicated", a ternary should be avoided, for readability and maintainability reasons – Taplar Commented Mar 8, 2019 at 19:29
  • baz = (foo > bar) ? (foo - bar) : (foo + bar) ? – el-teedee Commented Mar 8, 2019 at 19:35
  • @Taplar maybe you are right! But please take a look on real code example that I'd like to "enhance" – Pavel T Commented Mar 8, 2019 at 19:42
Add a ment  | 

6 Answers 6

Reset to default 4

You could convert the check to a number or take -1 as factor.

baz = foo + (foo > bar || -1) * bar

The cleanest approach is to use an object with the operands and a check for getting the operands.

op = {
    true: function (a, b) { return a + b; }, // add
    false: function (a, b) { return a - b; } // sub
}
baz = op[foo > bar](foo, bar);

You can remove the if-else and Math.abs to just this:

h = gradientStartH - (gradientStartH - gradientEndH) / arr.length * i

Here's a snippet paring it with your code:

// Your code 
function getDiffExisting(gradientStartH, gradientEndH, arr) {
  let h = 0;
  
  if (gradientStartH > gradientEndH) {
    h = gradientStartH - Math.abs(gradientStartH - gradientEndH) / arr.length
  } else {
    h = gradientStartH + Math.abs(gradientStartH - gradientEndH) / arr.length
  }
  
  return h;
}

console.log(getDiffExisting(200, 100, [1,2]))
console.log(getDiffExisting(50, 100, [1,2]))

function getDiffNew(gradientStartH, gradientEndH, arr) {
  let h = gradientStartH - (gradientStartH - gradientEndH) / arr.length
  return h;
}

console.log(getDiffNew(200, 100, [1,2]))
console.log(getDiffNew(50, 100, [1,2]))

(I have removed the i for testing purposes)

baz = foo > bar ? foo - bar : foo + bar;

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

EDIT:

I understand your specific question. I'm pretty sure I'm going to get lynched for saying this, but you could use eval() to evaluate it as a string. Not remend, if any of the below derives via unsantized user data.

h = eval(`${gradientStartH} ${gradientStartH > gradientEndH ? '-' : '+'} ${Math.abs(gradientStartH - gradientEndH) / arr.length * i}`);

Otherwise a decent two liner. Preferred.

const absVal = Math.abs(gradientStartH - gradientEndH) / arr.length * i;
h = gradientStartH > gradientEndH ? gradientStartH - absVal : gradientStartH + absVal;

You were almost there. foo - bar could be written as foo + -bar. So the pseudo code could be written as:

baz = foo + (foo > bar ? +1 : -1) * bar

Something like this,

baz = foo > bar ? foo - bar : foo + bar

You could use a ternary operator, as you attempted in your original answer. The syntax for a ternary operator should be condition ? true : false;

baz = foo > bar ? foo-bar : foo+bar;

You mentioned that it "might be much more plicated than this" which does not allow much clarity for a solution. Ternary operators likely will not work depending on the plexity. You can read more about ternary operators here.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>