feat: add state sync

This commit is contained in:
Richard 2024-02-27 22:20:18 -08:00
parent 5fe86ef030
commit 17a8c48e54
9 changed files with 262 additions and 0 deletions

42
src/sync/patch.luau Normal file
View file

@ -0,0 +1,42 @@
local NONE = { __none = "__none" }
local function diff(previousState: { [any]: any }, nextState: { [any]: any })
local patch = table.clone(nextState)
for key, previous in previousState do
local next = nextState[key]
if previous == next then
patch[key] = nil
elseif next == nil then
patch[key] = NONE
elseif type(previous) == "table" and type(next) == "table" then
patch[key] = diff(previous, next)
end
end
return patch
end
local function apply(state: { [any]: any }, patchState: { [any]: any })
local nextState = table.clone(state)
for key, patch in patchState do
local current = nextState[key]
if type(patch) == "table" and patch.__none == "__none" then
nextState[key] = nil
elseif type(patch) == "table" and type(current) == "table" then
nextState[key] = apply(current, patch)
else
nextState[key] = patch
end
end
return nextState
end
return {
diff = diff,
apply = apply,
}