0

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();
}
4
  • This actually doesn’t look so bad. Commented Nov 17, 2020 at 2:52
  • Yeah, it doesn't, but I'm gonna add more, and it would make the code longer. Commented Nov 17, 2020 at 3:01
  • npng, npdf = normalized.substring(0, 3); looks bad. ;) Commented Nov 17, 2020 at 3:02
  • @TheCodingWolfito No that line does not do what you think it does. console.log('npng', npng); Commented Nov 17, 2020 at 13:36

2 Answers 2

4

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

why not includes?
The length of the substrings changes, so you'd need a regex or something to extract the match from the start of the string to use .includes. I think startsWith and find would be a bit less ugly
0

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" });

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.