JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
JavaScript
// Algorithm: Linear Search for Earliest Timeout ID
// Complexity: O(n) time, O(1) space
/**
* Function to find the earliest timeout timestamp.
*
* @param {Array} intervals - An array of intervals with id, startTime, and endTime.
* @param {number} timeout - The timeout duration.
* @returns {number|null} - The ID associated with the earliest timeout timestamp or null if none found.
Description and Step-by-Step Explanation:
Helper Function (hasValidTimeout):
A helper function is created to check if an interval has a valid timeout.
Recursive Function (findEarliest):
The main functionality is moved into a recursive function.
It takes the remaining intervals and the current earliest timeout as parameters.
The base case checks if there are no more intervals to check.
Recursive Iteration through Intervals:
The first interval is destructured from the remaining intervals.
The current timeout is calculated.
If the interval has a valid timeout, compare and update the earliest timeout.
Result:
The recursive function is initially called with the first interval and initial values.
Example Usage:
The function is used with the provided example intervals and timeout.
*/
function findEarliestTimeoutTimestamp(intervals, timeout) {
// Helper function to check if an interval has a valid timeout
const hasValidTimeout = ({ startTime, endTime }, currentTimeout) =>
currentTimeout < endTime;
// Recursive function to iterate through intervals and find earliest timeout ID
const findEarliest = (remainingIntervals, currentEarliest) => {
// Base case: No more intervals to check
if (remainingIntervals.length === 0) {
return currentEarliest;
}
// Destructure the first interval
const [currentInterval, ...rest] = remainingIntervals;
const { id, startTime, endTime } = currentInterval;
// Calculate the current timeout timestamp
const currentTimeout = startTime + timeout;
// Check if the current interval has a valid timeout
...