Refactor ScriptIterator
This commit is contained in:
parent
cb2b566388
commit
c7a6823896
@ -5,64 +5,46 @@ namespace PkmnLib.Dynamic.ScriptHandling;
|
|||||||
public class ScriptIterator : IEnumerable<ScriptContainer>
|
public class ScriptIterator : IEnumerable<ScriptContainer>
|
||||||
{
|
{
|
||||||
private readonly IReadOnlyList<IEnumerable<ScriptContainer>> _scripts;
|
private readonly IReadOnlyList<IEnumerable<ScriptContainer>> _scripts;
|
||||||
private int _index = -1;
|
|
||||||
private int _setIndex = -1;
|
|
||||||
|
|
||||||
public ScriptIterator(IReadOnlyList<IEnumerable<ScriptContainer>> scripts)
|
public ScriptIterator(IReadOnlyList<IEnumerable<ScriptContainer>> scripts)
|
||||||
{
|
{
|
||||||
_scripts = scripts;
|
_scripts = scripts;
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IncrementToNext()
|
private IEnumerable<ScriptContainer> GetAsEnumerable()
|
||||||
{
|
{
|
||||||
if (_index != -1)
|
foreach (var enumerable in _scripts)
|
||||||
{
|
{
|
||||||
var current = _scripts[_index];
|
if (enumerable is IScriptSet set)
|
||||||
if (current is IScriptSet)
|
|
||||||
{
|
{
|
||||||
_setIndex += 1;
|
// We can't assume that the set remains the same size, so we need to iterate through it
|
||||||
if (_setIndex >= current.Count())
|
// 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 />
|
/// <inheritdoc />
|
||||||
public IEnumerator<ScriptContainer> GetEnumerator()
|
public IEnumerator<ScriptContainer> GetEnumerator()
|
||||||
{
|
{
|
||||||
if (_scripts.Count == 0)
|
return GetAsEnumerable().GetEnumerator();
|
||||||
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")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
|
Loading…
x
Reference in New Issue
Block a user