Refactor ScriptIterator

This commit is contained in:
Deukhoofd 2024-07-28 11:56:34 +02:00
parent cb2b566388
commit c7a6823896
1 changed files with 20 additions and 38 deletions

View File

@ -5,64 +5,46 @@ namespace PkmnLib.Dynamic.ScriptHandling;
public class ScriptIterator : IEnumerable<ScriptContainer>
{
private readonly IReadOnlyList<IEnumerable<ScriptContainer>> _scripts;
private int _index = -1;
private int _setIndex = -1;
public ScriptIterator(IReadOnlyList<IEnumerable<ScriptContainer>> scripts)
{
_scripts = scripts;
}
private bool IncrementToNext()
private IEnumerable<ScriptContainer> GetAsEnumerable()
{
if (_index != -1)
foreach (var enumerable in _scripts)
{
var current = _scripts[_index];
if (current is IScriptSet)
if (enumerable is IScriptSet set)
{
_setIndex += 1;
if (_setIndex >= current.Count())
// We can't assume that the set remains the same size, so we need to iterate through it
// with a for loop.
for (var j = 0; j < set.Count; j++)
{
_setIndex = -1;
var script = set.At(j);
// We can ignore empty scripts.
if (script.IsEmpty)
continue;
yield return script;
}
else
}
else
{
foreach (var script in enumerable)
{
return true;
// We can ignore empty scripts.
if (script.IsEmpty)
continue;
yield return script;
}
}
}
_index += 1;
for (; _index < _scripts.Count; _index++)
{
switch (_scripts[_index])
{
case IScriptSet:
_setIndex = 0;
return true;
case ScriptContainer { IsEmpty: false }:
return true;
}
}
return false;
}
/// <inheritdoc />
public IEnumerator<ScriptContainer> GetEnumerator()
{
if (_scripts.Count == 0)
yield break;
while (IncrementToNext())
{
var current = _scripts[_index];
yield return current switch
{
IScriptSet set => set.At(_setIndex),
ScriptContainer container => container,
_ => throw new InvalidOperationException("Invalid script type")
};
}
return GetAsEnumerable().GetEnumerator();
}
/// <inheritdoc />