Home > OS >  Why is the result in my function and the result at direct console.log is different?
Why is the result in my function and the result at direct console.log is different?

Time:01-06

I am doing a challenge, I don't want the solution of the challenge but I am missing something. I am trying to loop over an object and compare its entries with a given array. Here is the code.

function score(dice){
 let res;
 const diceStr = ""   dice.sort();

 const states = {
   1000: [1, 1, 1],
    600: [6, 6, 6],
    500: [5, 5, 5],
    400: [4, 4, 4],
    300: [3, 3, 3],
    200: [2, 2, 2],
    100: [1],
    50: [5],
  }

  for(const [key,entry] of Object.entries(states)){
  if(diceStr.includes(entry.toString())) res = key
  else res = 0
  }
  return res;

}

`

console.log(score([4, 4, 4, 3, 3]));

With this entry the result should be 400, but it isn't and I don't understand why. As I said before I just need to know the reason behind this bug. I didn't say, what is the goal of this challenge or where did I get it, -even though it looks so obvious- because I don't want the solution of the challenge. I just can't see my mistake here.

Here is another log which I think the exact same thing must be came out from the function and it's result is true in the console.

console.log('3,3,4,4,4'.includes('4,4,4'));

If this is a duplicate question, or there is any way that I could realize the bug here indirectly, please direct me to that document or question.
Thank you for your time.

CodePudding user response:

Instead of using the for loop, I would suggest using find function.

function score(dice){
 let res = [0];
 const diceStr = ""   dice.sort();

 const states = {
   1000: [1, 1, 1],
    600: [6, 6, 6],
    500: [5, 5, 5],
    400: [4, 4, 4],
    300: [3, 3, 3],
    200: [2, 2, 2],
    100: [1],
    50: [5],
  }



    res = Object.entries(states).find(each => {
        const [key,entry] = each
        return diceStr.includes(entry.toString())
    })
  return res[0];
}

This makes the code cleaner and more readable and you don't have to worry about the else condition.

  • Related