Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to work through a particular function written in Javascript, I realized that I'm facing challenges as the output is only an empty array []. Here's the problem statement, code snippet, and the actual output:
Challenging Problem Statement
The task is to create a method that takes an integer array as input and processes each number accordingly. The function should return a new array based on specific rules: If the number has a perfect square root, use that value; otherwise, square the number. For example, given [4,3,9,7,2,1], the expected output is [2,9,3,49,4,1]
The Troubling CODE
function squareOrSquareRoot(array) {
var newValues = [];
for (i = 0; i < array.length; i++){
var initial = array[i];
var sqrt = Math.sqrt(initial);
if (Number.isInteger(sqrt)){
newValues.push[sqrt];
}
else {
newValues.push[initial*initial];
}
}
return newArray;
}
Puzzling OUTPUT
Expected Output: '[2, 9, 3, 49, 4, 1]', Actual Output: '[]'
Expected Output: '[10, 10201, 25, 25, 1, 1]', Actual Output: '[]'
Expected Output: '[1, 4, 9, 2, 25, 36]', Actual Output: '[]'