Banal problem but I need some elucidation

Banal problem but I need some elucidation
0

#1

So, I was tackling the “Write Higher Order Arrow Functions” challenge, and while unfortunately, I wasn’t able to solve it, even looking at the basic solution didn’t clarify everything. More specifically, there’s this line that while I can understand what it does, I don’t understand why it does what it does in the context of the challenge.

Here is the proposed solution:

  const squareList = (arr) => {
      "use strict";
      const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
      return squaredIntegers;
    };

And here is the snippet I can’t grasp:

&& num % parseInt(num) === 0 )

Thanks in advance for any answer!


#2

parseInt makes sure we have an integer value of num. So, if num is 4.3, parseInt(num) will result in 4. Then we do a modulus operation. The idea is to check that num itself is an integer. If num is an integer, then the expression num % parseInt(num) will evaluate to 0 since any number divided by itself leaves no remainder.


#3

so this line calls filter which requires a function to be passed in - the function must return a boolean (true or false) and based on that, the current element being acted on is either kept or dropped
The current element then is called ‘num’.

First thing happening is
Is num > 0 AND (that’s this &&) is num an integer?
If yes, return true, otherwise return false.

Finally the returned and filtered array has a map applied to it in order to square each number that remains.

Edit: the part that checks if it is an integer could have been re-written with a function called Number.isInteger which would have been much more readable of course.


#4

So parseInt is not actually enough to ensure that num is an integer?


#5

you can read about parseInt and how it works in the MDN online docs


#6

Another approach is to check if num is equal to parseInt(num). If they are equal, then you know num is an integer.


#7

You could use parseInt to ensure that all of the given numbers are integers, but that doesn’t tell you anything about what they were before.

['1', 2.3, '4.5.6'].map((num) => parseInt(num)) // [1, 2, 4]

#8

Thank you all, it got clearer now!

Which is what I did but despite this, I still couldn’t grasp parseInt in the context of the exercise, and that’s probably my own fault.


#9

When that happens in future, just add some logs to log every term you see and the result of combing terms. This will allow you to see the code in action and clarify context.