function avoidObstacles(nums) {
// Sort the array
var sortArray = nums.sort();
// Find max number in array. Use destructuring assignment to extract data from arrays as
distinct variables
var maxNum = Math.max(...nums);
// Loop over sorted array by jump length
for (let i = 1; i < maxNum + 1; i++) {
var currentPlace = i;
// Check if jump has resulted in hitting obstacle (currentPlace = one of the numbers in the
array)
if (nums.includes(currentPlace)) {
// Try different jump length by going to next iteration
continue
}
else {
// Keep jumping until obstacle is hit
while (currentPlace < maxNum +1){
currentPlace += i;
// Go to next jump length if obstacle is hit
if (nums.includes(currentPlace)) {
break;
}
}
if (currentPlace > maxNum){
// Return successful jump length
return i;
break;
}
}
}
}
/**
* Test Suite
*/
describe('avoidObstacles()', () => {
it('returns minimal number of jumps in between numbers', () => {
// arrange
const nums = [5, 3, 6, 7, 9];
// act
const result = avoidObstacles(nums);
// log
console.log("result: ", result);
// assert
expect(result).toBe(4);
});
});