65 lines
1.8 KiB
C#
65 lines
1.8 KiB
C#
using System.Linq;
|
|
|
|
namespace BITKit
|
|
{
|
|
public interface IObjectElement<TKey, TValue>
|
|
{
|
|
bool IsMatch(TKey[] key);
|
|
TValue GetValue();
|
|
}
|
|
public interface IObjectMatcher<TKey, TValue>
|
|
{
|
|
bool TryMatch(out TValue value, TKey[] key);
|
|
}
|
|
[System.Serializable]
|
|
public record ObjectElement<TKey, TValue> : IObjectElement<TKey, TValue>
|
|
{
|
|
public ObjectElement()
|
|
{
|
|
|
|
}
|
|
public ObjectElement(TValue value, params TKey[] keys)
|
|
{
|
|
this.values = value;
|
|
this.keys = keys;
|
|
}
|
|
public ObjectElement(TKey[] key, TValue value)
|
|
{
|
|
this.keys = key;
|
|
this.values = value;
|
|
}
|
|
public string name;
|
|
public TKey[] keys;
|
|
public TValue values;
|
|
public TValue GetValue() => values;
|
|
public bool IsMatch(TKey[] key)
|
|
{
|
|
return MathE.Contains(key,keys);
|
|
}
|
|
}
|
|
public class ObjectMatcher<TKey, TValue> : IObjectMatcher<TKey, TValue>
|
|
{
|
|
public IObjectElement<TKey, TValue>[] list;
|
|
public void Add(IObjectElement<TKey, TValue> element)
|
|
{
|
|
var list = this.list.ToList();
|
|
list.Add(element);
|
|
this.list = list.ToArray();
|
|
}
|
|
public bool TryMatch(out TValue value, params TKey[] key)
|
|
{
|
|
var result = TryMatch(out TValue[] values, key);
|
|
value = values.FirstOrDefault();
|
|
return result;
|
|
}
|
|
public bool TryMatch(out TValue[] values, params TKey[] key)
|
|
{
|
|
values = list
|
|
.Where(x => x.IsMatch(key))
|
|
.Select(x => x.GetValue())
|
|
.ToArray();
|
|
|
|
return values is not null && values.Length > 0;
|
|
}
|
|
}
|
|
} |