I'm learning javascript on FreecodeCamp. And, the solution of my problem doesn't help me more. We have to filter integers in an array which is saved in const variable.
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
"use strict";
const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
and I cannot understand really this part num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
Why using parseint() method and Math.pow. Someone could explain me why?
thanks.
parseInt(num)
gives an integer part of num, for example, parseInt(3.14) === 3 //true
.
Using num % parseInt(num)
basically gives a difference between the number and its integer part. If it isn't 0
, the number is thrown out.
Math.pow(num)
gives a squared number, which is returned to the new array. Though, num * num
is faster in that regard, not having to include a module and to call an object property.
Other than that, the code is very crammed in the solution, and I would suggest to break it down to improve readability. Seems like the style in which it is written adds to the confusion.