Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I reduce duplication in my JavaScript if syntax?

I want to reduce duplication in my JavaScript syntax.

No matter how much I think about it, it doesn’t come to mind.

It doesn’t matter if it is for loop or any syntax!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i add some of case and result

if if it is correct answer would be result

    //   case 1

  //  const max = [1, 31, 0, 0]

  //  const min = [1, 31];
  
  //  result = [3, 5]

  //   case 2

  // const max = [0, 0, 0, 0, 0, 0]

  // const min = [0, 0]

  //  result = [1, 6]

  //   case 3

  // const max = [45, 4, 35, 20, 3, 9]

  // const min = [45, 4, 35, 20, 3, 9]
  
  //  result = [1, 1]

    if (max.length === 6) {
      answer[0] = 1;
    } else if (max.length === 5) {
      answer[0] = 2;
    } else if (max.length === 4) {
      answer[0] = 3;
    } else if (max.length === 3) {
      answer[0] = 4;
    } else if (max.length === 2) {
      answer[0] = 5;
    } else {
      answer[0] = 6;
    }

    if (min.length === 6) {
      answer[1] = 1;
    } else if (min.length === 5) {
      answer[1] = 2;
    } else if (min.length === 4) {
      answer[1] = 3;
    } else if (min.length === 3) {
      answer[1] = 4;
    } else if (min.length === 2) {
      answer[1] = 5;
    } else {
      answer[1] = 6;
    }

>Solution :

const getAnswers = x => (x < 1 || x > 6) ? 6 : 7 - x;

//   case 1
let max = [1, 31, 0, 0]
let min = [1, 31];
//  result = [3, 5]
let answer = [getAnswers(max.length), getAnswers(min.length)];
console.log('max.length: ', max.length, ' min.length: ', min.length, ' answer array: ', answer);

//   case 2
max = [0, 0, 0, 0, 0, 0]
min = [0]
//  result = [1, 6]
answer = [getAnswers(max.length), getAnswers(min.length)];
console.log('max.length: ', max.length, ' min.length: ', min.length, ' answer array: ', answer);

//   case 3
max = [45, 4, 35, 20, 3, 9]
min = [45, 4, 35, 20, 3, 9]
//  result = [1, 1]
answer = [getAnswers(max.length), getAnswers(min.length)];
console.log('max.length: ', max.length, ' min.length: ', min.length, ' answer array: ', answer);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading