Number Guesser for Javascript

Hey, I have just started and I have a question about the Number Guesser project.

My compareGuesses function is totally different then the solution one.
But it works. So the question is, is my solution bad way doing it?

This is the link:

Thank you for the answers!

My code:

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
const generateTarget = () => {
 return Math.floor(Math.random()*10) 
};

const compareGuesses = (human, computer, secret) =>{
  if (Math.abs(human - secret) < Math.abs(computer - secret)){
    return true;
  }
  if( Math.abs(human - secret) === Math.abs(computer - secret)){
     return true;
     }
  else{
    return false;
  }
};

const updateScore = winner => {
 if( winner === "human") {
  humanScore += 1; 
 }
  else{
   computerScore += 1;
  }
};

const advanceRound = () =>{
currentRoundNumber += 1;
};
1 Like

Hello, @py0633377077.

Welcome to the forums!

Your function is an acceptable way of accomplishing the task. It produces the expected outcome perfectly well. It could be refactored to be significantly more concise if you have the desire to do so. Consider this example:

const compareVals = (val1, val2) => val1 <= val2 //concise body arrow function

//could also be written:
/*
const compareVals = (val1, val2) => {
  return val1 <= val2
}
*/

console.log(compareVals(5, 6)) //true
console.log(compareVals(5, 5)) //true
console.log(compareVals(5, 4)) //false

The expression val1 <= val2 is evaluated, and that result is returned. To apply this to your code, keep in mind that val1 and val2 could also be expressions. You are currently comparing expressions like this:

What happens if you do the following instead?

return Math.abs(human - secret) < Math.abs(computer - secret)

An understanding of the above will help you to reduce the need to ever return true or return false. Doing so basically looks like this:

if (true) {
  return true
} else {
  return false
}

A bit redundant wouldn’t you say?

Happy Coding!

P.S. I edited your post to format your code so that it is easier to read. For future reference, see: How do I format code in my posts?

So… I reviewed the initial post on how the function could possibly look, but to be honest I completely got stuck on how to build the “compareGuesses” function. So, now I am feeling pretty dumb at this point. How do you even come to the conclusion that the function should be structured that way (I guess I do not know how to problem solve properly)?

I came up with this and it completely broke…

const compareGuesses = (user, cpu, targetNum) => {
  if (user === cpu) {
    return 'You Win!';
  } else if (targetNum >= Math.abs(user - targetNum) || targetNum < Math.abs(user - targetNum)) {
    return true;
    console.log('You Win!');
  } else if (target >= Math.abs(cpu - targetNum) || target < Math.abs(cpu - targetNum)) {
    return false;
    console.log('Computer Wins!');
  } else {
    return 'Error';
  }
};

… I kept getting my return value for " Error" . :sleepy: :cry:

One suggestion in the narrative is to abstract away the absolute difference to be a helper function.

const absDiff = (a, b) => Math.abs(a - b);

We’ll come back to this once we deal with the question, if the user wins on a tie, then do we need that conditional? Once we know the computer does not win we can default to the user.

    if (absDiff(cpu, targetNum) < absDiff(user, targetNum)) {
        return // ...computer wins
    }
    return // ...user wins

Have you caught on yet that anything after return is unreachable? It’s like the line never existed.

Hello All!
I took a little break from learning (which was bad on my part); I was just getting really frustrated and burnt out from the learning and projects. BUT I have returned back to my lesson! Trying to finish up this project in particular now, and after spending two days with it I feel like I have made some progress! I wanted to get another pair of eyes on my code. I am not getting the results I require to complete the project, so any suggestions would be greatly appreciated.

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:

// Random number generator: 0 - 9 / function one
const generateTarget = () => {
    let randomNum = Math.floor(Math.random() * 10);
    return randomNum;
};


const compareGuesses = (user, computer, target) => {
    if (Math.abs(user - target) <= Math.abs(computer - target)) {
        return 'User Wins!';
    } else if (Math.abs(user - target) < Math.abs(computer - target)) {
        return 'User Wins!';
    } else if (Math.abs(computer - target) < Math.abs(user - target)) {
        return 'Computer Wins!';
    } else {
        return 'Error!'
    }
};


// Increases the winner's score after each round / function three
const updateScore = () => {
    humanScore = ++0;
    computerScore = ++0;
    return `Score: User has ${humanScore} points. Computer has ${computerScore} points.`;
};


// Updates the round number after each round / function four
const advanceRound = () => {
    currentRoundNumber = ++1;
    return `Round: ${currentRoundNumber}`;
};


console.log(advanceRound());
console.log(compareGuesses(5, generateTarget(), generateTarget()));
console.log(updateScore());```

In my terminal, I get this error message:
SyntaxError: Invalid left-hand side expression in prefix operation
at wrapSafe (internal/modules/cjs/loader.js:1053:16)
at Module._compile (internal/modules/cjs/loader.js:1101:27)
at Object.Module._extensions…js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47

Hello mtf
could you please help me as i am not clear about > < ?
if (absDiff(cpu, targetNum) < absDiff(user, targetNum)) - is it not > in order to put ‘computer wins’ as it should be the nearest number to targetNum win ? i put numbers in this consideration, lets say targetNum is 5, cpu is 4 and user is 3. So absDiff (targetNum, cpu ) is 1 and absDiff (targetNum,user) is 2. 2 is near than 1 to targetNum so if absDiff (targetNum, cpu ) is < absDiff (targetNum,user) , should user be winning ?
My code is below but i am still not correct but i don’t know what to do anymore and i am stacked

.
I want to use ‘Booleans’ ‘true’ ‘false’ , just to try alternative but i am not sure i can use Booleans in this case ?
it kept on showing red colour and error so i cannot continue.

const compareGuesses = (‘human’,‘computer’,targetNum) => {
const userG= Math.abs (‘targetNum’-‘human’);
const computerG= Math.abs (‘targetNum’-‘computer’);

userG >= computerG? ‘true’:‘false’;

if (‘true’) {
return ‘human wins’
}
else {
return 'computer wins ’
}

Yes, 2 is nearer, but it is not the 2 we are looking at. It is the distance from 3 to 5. 4 is closer to 5 than 3 is.

I understand now, this is how I should consider, then I coded with Booleans but it didn’t go through. Where am i wrong? thanks

const compareGuesses = (‘human’,‘computer’,‘targetNum’) => {

const userG= Math.abs (‘human’-‘targetNum’);

const computerG= Math.abs (‘computer’-‘targetNum’);

‘userG’ <= ‘computerG’? ‘true’:‘false’;

}

Is there any particular reason why all the variables are written as strings?

Not really , i thought i should use string , i tried again without ’ ’ , but still is incorrect .

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
function gererateTarget() {
let round = Math.floor(Math.random()*9);
}

const compareGuesses = (human,computer,targetNum) => {

const userG= Math.abs (human-targetNum);
const computerG= Math.abs (computer-targetNum);

userG <= computerG? ‘true’:‘false’;
}

function updateScore (winner) {
if (‘winner’ === ‘human’) {
humanScore +=1;
else
{
computerScore +=1;
}
};

const advanceRound = () => {
currentRoundNumber += 1;

}

console.log(advanceRound);

There is no return from that function.

In truth, you wouldn’t need a ternary to return boolean primitives, the expression will do that for you.

return u < c

Also, note that you have written the booleans as strings. They are not strings.

1 Like

You’ve got an issue here as well. This function should return a random integer (0 - 9).

1 Like

so should be this ?
let round = Math.floor(Math.random()*10);
thanks

It already is that in the body of the function. You generate a random number just fine, but the number isn’t returned.

//either:
function generateTarget() {
  let round = Math.floor(Math.random() * 9);
  return round;
}
//or simply:
function generateTarget() {
  return Math.floor(Math.random() * 9);
}
//or if you're into concise body arrow functions
const generateTarget = () => Math.floor(Math.random() * 9);

Also check your spelling. The function name has to be generateTarget. The code that calls your function is in another file called game.js. If the name doesn’t match, the game won’t work.

sorry mtf, i don’t get it . Should i simply write like below as i don’t know what to do with Booleans anymore:)
if (userG<computerG) { return true: }
if (userG=computerG) (return true;}
else { return false;}

Thanks midlinder, now the code is working but I need to play it around if i am right or wrong:)

Could be,

if (userG <= computerG) return true
return false

As mentioned earlier, this will do the same thing…

    return userG <= computerG
1 Like

Thanks a lot mtf, now I totally understood.I prefer to use Booleans as it is shorter. I am slowly getting all these conditional things by practising like this.