using System; using System.Linq; namespace Unity.UIWidgets { public interface Dispatcher { T dispatch(object action); object dispatch(object action); } public class DispatcherImpl : Dispatcher { readonly Func _impl; public DispatcherImpl(Func impl) { _impl = impl; } public T dispatch(object action) { if (_impl == null) { return default; } return (T) _impl(action); } public object dispatch(object action) { if (_impl == null) { return default; } return _impl(action); } } public delegate State Reducer(State previousState, object action); public delegate Func Middleware(Store store); public delegate void StateChangedHandler(State action); public class Store { public StateChangedHandler stateChanged; readonly Dispatcher _dispatcher; readonly Reducer _reducer; State _state; public Store( Reducer reducer, State initialState = default, params Middleware[] middleware) { _reducer = reducer; _dispatcher = _applyMiddleware(middleware); _state = initialState; } public Dispatcher dispatcher { get { return _dispatcher; } } public State getState() { return _state; } Dispatcher _applyMiddleware(params Middleware[] middleware) { return middleware.Reverse().Aggregate, Dispatcher>( new DispatcherImpl(_innerDispatch), (current, middlewareItem) => middlewareItem(this)(current)); } object _innerDispatch(object action) { _state = _reducer(_state, action); if (stateChanged != null) { stateChanged(_state); } return action; } } }