I'm in a Codewars challenge, called 'zombie onslaught'.
The task is: given three arguments (n° of zombies, initial zombie position/distance, n° of ammo) I have to return a message based on some conditions.
If the zombies are all dead I should return: 'You killed all ${x} zombies'
If there are still zombies around but you run out of ammo I should return: 'You shot ${x} zombies before being eaten: ran out of ammo.'
if I've got ammo but the distance is 0 I should return 'You shot ${x} zombies before being eaten: overwhelmed.'
In the end if I've runned out of ammo and the distance is 0 too, I should return 'You shot ${x} zombies before being eaten: overwhelmed.'
Now the problem is that the message displays correctly in console.log(), but I need to return it, and the return is just an undefined
Here's the code, it's a short function so i post it all here.
function zombie_shootout(zombies, range, ammo) {
let currentZombies = zombies
let currentRange = range
let currentAmmo = ammo
let killedZombies = 0
let message = ''
setInterval(() => {
currentZombies -= 1
currentRange -= 0.5
currentAmmo -= 1
if (currentZombies === 0) {
message = `You shot all ${currentZombies} zombies`
} else if (currentZombies > 0 && currentAmmo === 0) {
killedZombies = zombies - currentZombies
message = `You shot ${killedZombies} zombies before being eaten: ran out of ammo.`
} else if (currentAmmo > 0 && currentRange === 0) {
killedZombies = zombies - currentZombies
message = `You shot ${killedZombies} zombies before being eaten: overwhelmed.`
} else if (currentAmmo === 0 && currentRange === 0) {
killedZombies = zombies - currentZombies
message = `You shot ${killedZombies} zombies before being eaten: overwhelmed.`
}
}, 1000)
return message
}
The message variable that is returned at the end it always returns undefined
Could you help me guys? Cause in the console the results are correct, so everything seems to work fine.
Here's some test cases
zombie_shootout(3, 10, 10) // => "You shot all 3 zombies."
zombie_shootout(100, 8, 200) // => "You shot 16 zombies before being eaten: overwhelmed."
zombie_shootout(50, 10, 8) // => "You shot 8 zombies before being eaten: ran out of ammo."
setInterval takes time and javascript is Synchronous by default, javaScript does not wait for the setInterval to execute. you can use async/await or promises