2

i have code like below,

if (filteredIds.length > 0) {
    notify({
        title: `${
            type === "type1"
                ? 'type1 checks'
                : 'type2 checks'
        } started.`,
    });
 } else {
     notify({
         title: `${
             type === "type1"
                 ? 'type1 checks'
                 : 'type2 checks'
         } have been already running on selected id.`,
     });
 }

the above code works. But i want to use ternary operator to be used instead of if and else as the notify thing seems to be repetitive.

i want something like having the ternary operator in notify itself to return necessary text based on filteredIds length and type.

notify({
    title: `${ //condition here
        type === "type1" 
            ? 'type1 checks'
            : 'type2 checks'
    } started.`,
});

Basically i want the if else code to be less code. Could someone help me with this. I am new to programming and not sure how to use nested ternary operator. thanks.

2
  • If I am understanding it correctly, your conditional strings are have been already running on selected id. and started based on length of filteredId? Commented Aug 14, 2021 at 6:53
  • yes thats right. Commented Aug 14, 2021 at 6:55

3 Answers 3

1

Are you looking for a conditional expression like this?

notify({
    title: `${
        type === "type1" 
            ? 'type1 checks'
            : 'type2 checks'
    } ${filteredIds.length? 'started' : 'have been already running on selected id'}.`,
});
Sign up to request clarification or add additional context in comments.

Comments

1

if/else

if (filteredIds.length > 0) {
    notify({
        title: `${
            type === "type1"
                ? 'type1 checks'
                : 'type2 checks'
        } started.`,
    });
 } else {
     notify({
         title: `${
             type === "type1"
                 ? 'type1 checks'
                 : 'type2 checks'
         } have been already running on selected id.`,
     });
 }

ternary expression

 notify({
   title: `${
     type === "type1"
       ? 'type1 checks'
       : 'type2 checks'
   } ${filteredIds.length ? 'started.' : 'have been already running on selected id.'}`,
 });

Comments

0
interface Result {
  title: string
}

const notify = (title: string): Result => {
  // checking condition logic
  // if (type) {
  // ...
  // }
  return {title: 'your result here'}
}

And then

notify('argument')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.