Skip to content

Instantly share code, notes, and snippets.

@lkaczanowski
Last active November 3, 2019 11:35
Show Gist options
  • Save lkaczanowski/0cd0cb0a21f5bd817f8e to your computer and use it in GitHub Desktop.
Save lkaczanowski/0cd0cb0a21f5bd817f8e to your computer and use it in GitHub Desktop.
Method to generate infinite iterations of elements with IEnumerable and IAsyncEnumerable
public static class SequenceGenerator
{
public static IEnumerable<T> Generate<T>(T initialValue, Func<T, T> generator)
where T : struct
{
var value = initialValue;
while (true)
{
yield return value;
value = generator(value);
}
}
public static async IAsyncEnumerable<T> Generate<T>(T initialValue, Func<T, ValueTask<T>> generator)
where T : struct
{
var value = initialValue;
while (true)
{
yield return value;
value = await generator(value);
}
}
public static async IAsyncEnumerable<TK> Generate<T, TK>(T initialValue, Func<T, T> inputGenerator, Func<T, Task<TK>> resultGenerator)
where T : struct
{
var value = initialValue;
while (true)
{
var result = await resultGenerator(value);
yield return result;
value = inputGenerator(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment