ActuatorDigital / Fluxity

It's Flux, in Unity (using Flume)
3 stars 1 forks source link

Util/helper for state that is a set #57

Open stevehalliwell opened 3 weeks ago

stevehalliwell commented 3 weeks ago

Describe the task

We have frequently found that we want a set of x, with a command to add and remove, and a reducer to execute that. Is it worth looking at building a generic or code gen, etc. that makes this more direct and ensures consistency.

stevehalliwell commented 3 weeks ago

e.g.

public class SetState<T>
{
    public struct State
    {
        public List<T> List;
        public static State Create()
        {
            return new State
            {
                List = new List<T>()
            };
        }
    }

    public class AddCommand : ICommand
    {
        public IReadOnlyCollection<T> Items;
    }

    public class RemoveCommand : ICommand
    {
        public IReadOnlyCollection<T> Items;
    }

    public class ClearCommand : ICommand
    {
    }

    public static class Reducers
    {
        internal static void RegisterAll(FluxityRegisterFeatureContext<State> context)
        {
            context
                .Reducer<AddCommand>(HandleAdd)
                .Reducer<RemoveCommand>(HandleRemove)
                .Reducer<ClearCommand>(HandleClear)
                ;
        }

        public static State HandleAdd(State state, AddCommand command)
        {
            state.List.AddRange(command.Items);
            return state;
        }

        public static State HandleRemove(State state, RemoveCommand command)
        {
            foreach (var item in command.Items)
            {
                state.List.Remove(item);
            }
            return state;
        }

        public static State HandleClear(State state, ClearCommand command)
        {
            state.List.Clear();
            return state;
        }
    }
}