Search Insert Position in TypeScript

function searchInsert(nums: number[], target: number): number {
    // Initialize 'start' and 'end' pointers to the beginning and end of the array.
    let start = 0;
    let end = nums.length - 1;

    // The loop continues until 'start' is greater than 'end', indicating the entire array has been searched.
    while (start <= end) {
        // Calculate the middle index of the current range.
        // We use Math.floor to ensure we get an integer value for the index.
        let mid = Math.floor((start + end) / 2);

        // If the element at the middle index is equal to the target, return the middle index.
        // This means the target is found in the array.
        if (nums[mid] === target) {
            return mid;
        }

        // If the target is less than the element at the middle index,
        // narrow the search to the left half of the array.
        // We do this by moving the 'end' pointer to just before the middle index.
        if (target < nums[mid]) {
            end = mid - 1;
        } else {
            // If the target is greater than the element at the middle index,
            // narrow the search to the right half of the array.
            // We do this by moving the 'start' pointer to just after the middle index.
            start = mid + 1;
        }
    }

    // If we exit the loop without finding the target, 'start' will be at the position
    // where the target should be inserted to maintain the array's sorted order.
    // This is because the loop narrows down the range to a point where 'start' and 'end' cross each other.
    // At this point, 'start' is at the smallest index greater than the target value.
    return start;
}

PrevNext