1
This commit is contained in:
66
Packages/Core/ObjectMatcher/ObjectMatcher.cs
Normal file
66
Packages/Core/ObjectMatcher/ObjectMatcher.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user