mirror of
https://github.com/littensy/charm.git
synced 2026-10-21 03:36:11 +00:00
feat: add state sync
This commit is contained in:
parent
5fe86ef030
commit
17a8c48e54
9 changed files with 262 additions and 0 deletions
42
src/sync/patch.luau
Normal file
42
src/sync/patch.luau
Normal 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,
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue