Calculate Total Itinerary Segments
At Ixigo, we help millions of users plan their travel with seamless itineraries. These itineraries can range from simple point-to-point journeys to complex multi-city or multi-country tours. To better understand the complexity and scope of a user's travel plan, we sometimes need to quantify the total number of individual 'segments' or 'points of interest' within an itinerary. An itinerary can be a single segment (represented by a numeric value, e.g., a travel duration or cost) or a composite itinerary containing a list of other itineraries, which themselves can be simple segments or further nested composite itineraries.
Your task is to implement a function calculateTotalSegments that takes a nested array representing a travel itinerary and returns the sum of all individual numeric segments found within it. The structure can be arbitrarily nested.
Function Signature:
type ItineraryItem = number | ItineraryItem[];
function calculateTotalSegments(itinerary: ItineraryItem[]): number
itinerary: A list where each element can either be a number (representing a single travel segment) or another list (representing a composite itinerary containing further ItineraryItems). Each number represents a value associated with that segment (e.g., points, duration, cost).number representing the sum of all individual numeric segments across the entire nested structure.itinerary will always be an array at the top level.[]) should contribute 0 to the total sum.Examples
Example 1
Input:
itinerary = [1, 2, 3]
Output:
6
Note:
The itinerary contains three simple segments: 1, 2, and 3. Their sum is 1 + 2 + 3 = 6.
Example 2
Input:
itinerary = [[1, 2], [3, [4, 5]]]
Output:
15
Note:
The itinerary sums up segments: 1 + 2 (from the first sub-list) + 3 (from the second sub-list) + 4 + 5 (from the nested sub-list) = 15.
Example 3
Input:
itinerary = [10, [], [20, [30, []]], 5]
Output:
65
Note:
Segments are 10, 20, 30, and 5. Empty lists contribute 0 to the sum. Total sum is 10 + 20 + 30 + 5 = 65.
Constraints
itinerary will only contain number types (positive integers) or array types.Loading editor...