
Kenneth Y. answered 09/24/19
Tutor
New to Wyzant
Experienced CS Tutor Specializing in Python, JavaScript, Ruby++
function closestDegreeFinder(x, degrees) {
//make a copy of degrees
let arr = [...degrees]
//Keep track of the position of the degree you want to return
//and the distance
let index = 0
let closestDistance = Infinity
//loop through array
for(let i = 0; i < arr.length; i++){
//Handle degrees greater than 360
while(arr[i] > 360){
arr[i] -= 360
}
//Calculate the absolute distance between the degree in
//the array and the given degree
let distance = Math.abs(arr[i] - x)
//if the distance is greater than 180, then the distance would
//be shorter ifwe calculate it from the other direction.
//In that case, subtract 360 from the distance and get
//its absolute value. Assign that value as the new
//shorter distance
if(distance > 180){
distance = Math.abs(distance - 360)
}
//if the distance is lower than the distance we thought
//was the closest, then that new distance is the closest
if(distance < closestDistance){
closestDistance = distance
index = i
}
}
//return the closest degree
return arr[position]
}
console.log(closestDegreeFinder(1, [10, 90, 200, 280, 355]))