Further work on static side
This commit is contained in:
52
PkmnLib.Static/Libraries/DataLibrary.cs
Normal file
52
PkmnLib.Static/Libraries/DataLibrary.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using PkmnLib.Static.Utils;
|
||||
|
||||
namespace PkmnLib.Static.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// A basic library for data types. Stores data both by name and by index.
|
||||
/// </summary>
|
||||
public abstract class DataLibrary<T>
|
||||
where T : INamedValue
|
||||
{
|
||||
private readonly Dictionary<StringKey, T> _data = new();
|
||||
private readonly List<T> _values = [];
|
||||
|
||||
/// <summary>
|
||||
/// Adds a value to the library.
|
||||
/// </summary>
|
||||
public void Add(T value)
|
||||
{
|
||||
_data.Add(value.Name, value);
|
||||
_values.Add(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a value from the library.
|
||||
/// </summary>
|
||||
public void Remove(T value)
|
||||
{
|
||||
_data.Remove(value.Name);
|
||||
_values.Remove(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try to get a value from the library. Returns false if the value is not found.
|
||||
/// </summary>
|
||||
public bool TryGet(StringKey key, [MaybeNullWhen(false)] out T value) => _data.TryGetValue(key, out value);
|
||||
|
||||
/// <summary>
|
||||
/// Get a random value from the library.
|
||||
/// </summary>
|
||||
public T GetRandom(IRandom random) => _values[random.GetInt(_values.Count)];
|
||||
|
||||
/// <summary>
|
||||
/// The number of values in the library.
|
||||
/// </summary>
|
||||
public int Count => _values.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the library is empty.
|
||||
/// </summary>
|
||||
public bool IsEmpty => _values.Count == 0;
|
||||
}
|
||||
Reference in New Issue
Block a user