Skip to content

Commit

Permalink
Better implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
mattjohnsonpint committed Aug 7, 2022
1 parent 1783626 commit 8b49bbd
Showing 1 changed file with 27 additions and 28 deletions.
55 changes: 27 additions & 28 deletions src/TimeZoneConverter/DataLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,40 +55,39 @@ public static void Populate(
}

// Expand the IANA map to include all links (both directions)
foreach (var link in links)
var linksToMap = links.ToList();
while (linksToMap.Count > 0)
{
var hasMapFromKey = ianaMap.TryGetValue(link.Key, out var mapFromKey);
var hasMapFromValue = ianaMap.TryGetValue(link.Value, out var mapFromValue);

if (hasMapFromKey && hasMapFromValue)
{
// There are already mappings in both directions
continue;
}

if (!hasMapFromKey && hasMapFromValue)
var retry = new List<KeyValuePair<string, string>>();
foreach (var link in linksToMap)
{
// Forward mapping
ianaMap.Add(link.Key, mapFromValue!);
continue;
}

if (!hasMapFromValue && hasMapFromKey)
{
// Reverse mapping
ianaMap.Add(link.Value, mapFromKey!);
continue;
}
var hasMapFromKey = ianaMap.TryGetValue(link.Key, out var mapFromKey);
var hasMapFromValue = ianaMap.TryGetValue(link.Value, out var mapFromValue);

if (hasMapFromKey && hasMapFromValue)
{
// There are already mappings in both directions
continue;
}

// This is a rare edge case, so it's worth just searching O(n)
foreach (var item in links)
{
if (item.Key != link.Key && item.Value == link.Value && ianaMap.TryGetValue(item.Key, out var mapFromItemKey))
if (!hasMapFromKey && hasMapFromValue)
{
// Forward mapping
ianaMap.Add(link.Key, mapFromValue!);
}
else if (!hasMapFromValue && hasMapFromKey)
{
ianaMap.Add(link.Key, mapFromItemKey);
break;
// Reverse mapping
ianaMap.Add(link.Value, mapFromKey!);
}
else
{
// Not found yet, but we can try again
retry.Add(link);
}
}

linksToMap = retry;
}

foreach (var item in railsMapping)
Expand Down

0 comments on commit 8b49bbd

Please sign in to comment.