using System.Collections;
using System.Text.Json;
namespace DeepDrftContent.FileDatabase.Utils;
///
/// A set implementation that uses structural equality for values by serializing them to JSON.
/// This provides the same behavior as the TypeScript StructuralSet.
///
/// The value type
public class StructuralSet : IEnumerable
{
private readonly Dictionary _innerMap = new();
///
/// Converts a value to its string representation for structural comparison
///
private string GetValueString(T value)
{
return value switch
{
null => "null",
string s => s,
int or long or float or double or decimal => value.ToString()!,
_ => JsonSerializer.Serialize(value)
};
}
///
/// Adds a value to the set
///
public StructuralSet Add(T value)
{
var valueString = GetValueString(value);
if (!_innerMap.ContainsKey(valueString))
{
_innerMap[valueString] = value;
}
return this;
}
///
/// Checks if the set contains the specified value
///
public bool Has(T value)
{
var valueString = GetValueString(value);
return _innerMap.ContainsKey(valueString);
}
///
/// Removes a value from the set
///
public bool Delete(T value)
{
var valueString = GetValueString(value);
return _innerMap.Remove(valueString);
}
///
/// Clears all values from the set
///
public void Clear() => _innerMap.Clear();
///
/// Gets the number of values in the set
///
public int Size => _innerMap.Count;
///
/// Enumerates all values in the set
///
public IEnumerator GetEnumerator()
{
return _innerMap.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
///
/// Gets all values in the set
///
public IEnumerable Values => _innerMap.Values;
}