vinum-team / Vinum

A modern reactive state management library for correctness and speed.
MIT License
16 stars 1 forks source link

Writable Object #13

Closed sinlerdev closed 1 year ago

sinlerdev commented 1 year ago

Writable is a simple object, which is nothing but a wrapper that allows you to write data to any stateful, but immutable object, such as Matches, Calcs, and Mirrors.

The motive behind this object is to allow powerful creation of reactive keys in groups- as currently, if we ever wanted to create a reactive key (assuming if we already implemented #9), we have to do the following:

local props = Group({
    MaxHealth = 100
}, AlwaysTrue)

local health = Hold(100, AlwaysTrue)
local healthCalc = Calc(function(_, useKeyState)
    local currentMaxHealth = useKeyState(props, "MaxHealth")
    health:set(currentMaxHealth)
    return 0
end, AlwaysTrue)

props:setKey("Health", health)

Although this isn't ideal, as we had to create two objects just to:

To solve this, it might be sensible to introduce a Writable object, which unlike Reflect, it allows you to write changes to the wrapped object.

Applying this feature on our example, we can see that a lot of the boilerplate code is mostly gone:

local props = Group({
   MaxHealth = 100
}, AlwaysTrue)

props:setKey("Health", Writable(Calc(function(_, useKeyState)
    return useKeyState(props, "MaxHealth")
end, AlwaysTrue)))