Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save babon/d56b1cc53c6dbe95868835e23bdb8323 to your computer and use it in GitHub Desktop.
Save babon/d56b1cc53c6dbe95868835e23bdb8323 to your computer and use it in GitHub Desktop.
//will throw like "[0], [1], [0], [1], [2] [0..1]"
public sealed class LastNQueue<T> : Queue<T>
{
public int HoldLastN { get; }
public LastNQueue(int holdLastN)
{
HoldLastN = holdLastN;
}
/// <summary>
/// If the total number of item exceed the capacity, the oldest automatically dequeues.
/// </summary>
/// <returns>The dequeued value, if any.</returns>
public new T Enqueue(T item)
{
base.Enqueue(item);
if (base.Count > HoldLastN)
{
return base.Dequeue();
}
return default;
}
}
public class CList<T> : List<T>
{
LastNQueue<int> lastNItems = new LastNQueue<int>(10);
void Throw(int index)
{
throw new UnityException($"{string.Join(", ", lastNItems.Select(x => $"[{x}]"))} 0..{base.Count - 1}");
}
public new T this[int index]
{
get
{
lastNItems.Enqueue(index);
if (index < 0 || index >= base.Count)
Throw(index);
return base[index];
}
set
{
lastNItems.Enqueue(index);
if (index < 0 || index > base.Count)
Throw(index);
base[index] = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment