Skip to content

Instantly share code, notes, and snippets.

@vritant24
Last active March 27, 2021 04:03
Show Gist options
  • Select an option

  • Save vritant24/0e39482ac2c91f6368d1f13eaacaf2b0 to your computer and use it in GitHub Desktop.

Select an option

Save vritant24/0e39482ac2c91f6368d1f13eaacaf2b0 to your computer and use it in GitHub Desktop.
An abstraction for easy Arithmetic and Geometric Progression creation in C#;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Streamable
{
public class Sequence<T> : IEnumerable<T>, IEnumerator<T>
{
private readonly Func<T, ulong, (T nextElement, bool isLast)> formulae;
private readonly T firstElement;
private bool isEnded;
private ulong index;
public Sequence(
Func<T, ulong, (T nextElement, bool isLast)> formulae,
T firstElement)
{
this.formulae = formulae;
this.firstElement = firstElement;
this.isEnded = false;
this.index = 0;
this.Current = this.firstElement;
}
#region IEnumerable
public T Current
{
get;
private set;
}
object IEnumerator.Current => this.Current;
private readonly object valueGate = new();
public bool MoveNext()
{
lock(valueGate)
{
if (isEnded)
{
return false;
}
this.index++;
(Current, isEnded) = formulae(Current, this.index);
}
return true;
}
public void Reset()
{
lock(valueGate)
{
this.isEnded = false;
this.index = 0;
this.Current = this.firstElement;
}
}
#endregion
#region IEnumerable
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
#endregion
public void Dispose()
{
// Nothing to dispose
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment