ghost icon indicating copy to clipboard operation
ghost copied to clipboard

return inside while loop should be useable

Open kaidesu opened this issue 4 years ago • 0 comments

Currently, if using a return within a while loop, nothing happens. For example, the follow doesn't work when returning the pivot value directly:

function search(numbers, value) {
  left = 0
  right = numbers.length() - 1
  
  while (left <= right) {
    pivot = left + ((right - left) / 2).round()

    if (numbers[pivot] == target) {
      return pivot // this should exit the loop and return the value
    }

    if (value < numbers[pivot]) {
      right = pivot - 1
    } else {
      left = pivot + 1
    }
  }

  return -1
}

print(search([1, 2, 3], 2)) // should return 1

kaidesu avatar Feb 12 '22 05:02 kaidesu