More efficient code for Future HHV with variable period

I need help rewriting this to make it faster, not sure if possible.
This is for an intraday formula. Essentially, I need to have the future HHV up to the end of the intraday session. The first bar of the after hours session is flagged to calculate the periods remaining:

after_hours_first_bar_number = ValueWhen(is_after_hours_first_bar, bar_number, 0);
bars_to_end_regular_session = after_hours_first_bar_number - bar_number;

I have written the quick hack version found in the forum and it works:

function futureHHV( array, periods )
{
   return Ref( HHV( array, periods ), periods );
}


function futureHHV_variable_period(array, periodI have  )
{
	minperiod = LastValue( Lowest( period ) );
	maxperiod = LastValue( Highest( period ) );
	
	result = Null;
	
	for( p = minperiod; p <= maxperiod; p++ )
	{	
		ind = futureHHV(array, p );
		
		result = IIf( period == p, ind, result );
	}
	
	return result;
}

upcoming_highest_high = futureHHV_variable_period(H, bars_to_end_regular_session);

But the code is too slow. Having a headache trying to rewrite as a fully vectorized version. Not even sure if possible.

Any ideas on how to eliminate the loop, please? Thanks

Did you search the forum before posting?

It looks like the solution to your problem was already there: