LeWolfie
LeWolfie

Reputation: 82

Simplify nested if/else conditionals (JS)

I want to simplify this nested if/else conditionals or statements, but I don't know-how because I want them easier to read and more practical. I'm just a freshman at programming. That's why I get stuck with this spaghetti code.

setmessage = 'You have requested that the file type of the site screenshot be:'

normalized = message.content.toLowerCase();
npng, npdf = normalized.substring(0, 3);
nhtml = normalized.substring(0, 4);

if (npng == 'png') {
   message.channel.send(setmessage + '**PNG**');
   areyousure();
} else if (npdf == 'pdf') {
   message.channel.send(setmessage + '**PDF**');
   areyousure();
} else if (nhtml == 'html') {
   message.channel.send(setmessage + '**HTML**');
   areyousure();
} else {
   message.channel.send(invalidmessage);
   getouttahere();
}

Upvotes: 0

Views: 196

Answers (2)

epascarello
epascarello

Reputation: 207501

Using a reg expression you can match the start of the string.

function test(message) {

  var extension = message.content.match(/^(pdf|jpg|html)/);
  if (extension) {
    console.log(extension[1].toUpperCase());
   // message.channel.send(setmessage + '**' + extension[1].toUpperCase() + '**');
    // areyousure();
  } else {
     console.log('invalid');
     // message.channel.send(invalidmessage);
     // getouttahere();
  }
}


test({ content : "pdf" });
test({ content : "jpg" });
test({ content : "html" });
test({ content : "sh" });

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

Make an array of the possible substrings the message starts with, and use .find to see the substring that matches. If there is one, call .send with it - otherwise, pass in invalidmessage.

const permittedExtensions = ['png', 'pdf', 'html'];
const normalized = message.content.toLowerCase();
const ext = permittedExtensions.find(ext => normalized.startsWith(ext));
if (ext) {
  message.channel.send(setmessage + '**' + ext.toUpperCase() + '**');
  areyousure();
} else {
   message.channel.send(invalidmessage);
   getouttahere();
}

Upvotes: 4

Related Questions