Add function to extract information from season keys

This commit is contained in:
Tim Van Baak 2024-08-15 08:51:17 -07:00
parent 4b2712e4bc
commit 566d29e539
2 changed files with 29 additions and 5 deletions

View File

@ -34,19 +34,33 @@ public class TimelineFactory(int nextTimeline)
/// <summary> /// <summary>
/// Convert a timeline serial number to its string identifier. /// Convert a timeline serial number to its string identifier.
/// </summary> /// </summary>
/// <param name="designation">Integer.</param> /// <param name="serial">Integer.</param>
/// <returns>Timeline identifier.</returns> /// <returns>Timeline identifier.</returns>
public static string IntToString(int designation) { public static string IntToString(int serial) {
static int downshift(int i ) => (i - (i % 26)) / 26; static int downshift(int i ) => (i - (i % 26)) / 26;
IEnumerable<char> result = [Letters[designation % 26]]; IEnumerable<char> result = [Letters[serial % 26]];
for (int remainder = downshift(designation); remainder > 0; remainder = downshift(remainder) - 1) { for (int remainder = downshift(serial); remainder > 0; remainder = downshift(remainder) - 1) {
// We subtract 1 after downshifting for the same reason we add 1 above after upshifting. // We subtract 1 after downshifting for the same reason we add 1 above after upshifting.
//
result = result.Prepend(Letters[(remainder % 26 + 25) % 26]); result = result.Prepend(Letters[(remainder % 26 + 25) % 26]);
} }
return new string(result.ToArray()); return new string(result.ToArray());
} }
/// <summary>
/// Extract the timeline and turn components of a season designation.
/// </summary>
/// <param name="seasonKey">A timeline-turn season designation.</param>
/// <returns>The timeline and turn components.</returns>
/// <exception cref="FormatException"></exception>
public static (string timeline, int turn) SplitKey(string seasonKey)
{
int i = 1;
for (; !char.IsAsciiDigit(seasonKey[i]) && i < seasonKey.Length; i++);
return int.TryParse(seasonKey.AsSpan(i), out int turn)
? (seasonKey[..i], turn)
: throw new FormatException($"Could not parse turn from {seasonKey}");
}
public TimelineFactory() : this(0) { } public TimelineFactory() : this(0) { }
public int nextTimeline = nextTimeline; public int nextTimeline = nextTimeline;

View File

@ -22,6 +22,16 @@ public class TimelineFactoryTest
Assert.That(TimelineFactory.StringToInt(designation), Is.EqualTo(number), "Incorrect number"); Assert.That(TimelineFactory.StringToInt(designation), Is.EqualTo(number), "Incorrect number");
} }
[TestCase("a0", "a", 0)]
[TestCase("a1", "a", 1)]
[TestCase("a10", "a", 10)]
[TestCase("aa2", "aa", 2)]
[TestCase("aa22", "aa", 22)]
public void SeasonKeySplit(string key, string timeline, int turn)
{
Assert.That(TimelineFactory.SplitKey(key), Is.EqualTo((timeline, turn)), "Failed to split key");
}
[Test] [Test]
public void NoSharedFactoryState() public void NoSharedFactoryState()
{ {