DEV Community

Cover image for Can you simplify this code for the guy?
Adeleye Ayodeji
Adeleye Ayodeji

Posted on

Can you simplify this code for the guy?

Interviewer: Write a function to print true if number is even, and false if odd.

Can you simplify this code for the guy?

Top comments (7)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

For a given array of numbers:

numbers.forEach( function (let el) {
(el%2 === 0) ? console.log('true') : console.log('false');
});

It's more or less the same than @mranyx did, it's correct. 0 returns even which is correct and floats are not odd nor even (only integers can be).

For that given array:
 [0, 1, 2, 3, 5.1, 4.3, 4.2]

it returns true, false, true, false, false, false false.

I just coded it and tried it on the browser's console while reading xD

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan • Edited

The ternary is unnecessary. The modulo operator already returns a boolean expression, so it's redundant. It's like saying "true or false ? true: false."

Here's a simplified version:

numbers.forEach(num => console.log(num % 2 === 0));
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

totally agree 😆
I took the other answer as start point only to figure out why the OP said it's incomplete, so i used a foreach for testing purposes and commented it "as is" 😅

Collapse
 
starboysharma profile image
Pankaj Sharma

I have two solutions:

  1. In this case, you should use switch case because they are faster in comparison of if-else statement and more cleaner syntax.

  2. But what if you don't want to write every time if else if try this

<?php
$compare_length = 20;
$match = 7;
for ($i = 1; $i < $compare_length) {
if ($match === $i) {
echo 'Match Found';
break;
}
}

?>

Collapse
 
mranyx profile image
MrAnyx • Edited

function even(int number) {
echo (number % 2 == 0) ? "true" : "false";
}

I hope he didn't go too far in the numbers 😂

Collapse
 
adeleyeayodeji profile image
Adeleye Ayodeji

Not completed

Collapse
 
adeleyeayodeji profile image
Adeleye Ayodeji

Why, how come?