From 210e9482255257ca90db1dc69d72b743aa54db65 Mon Sep 17 00:00:00 2001 From: littensy <56808540+littensy@users.noreply.github.com> Date: Sun, 11 May 2025 17:49:01 -0700 Subject: [PATCH] refactor: iterate over previous data in mapped --- pkgs/charm/src/mapped.luau | 12 ++++++++---- pkgs/charm/tests/mapped.spec.luau | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/pkgs/charm/src/mapped.luau b/pkgs/charm/src/mapped.luau index 247ae31..fa4f7f7 100644 --- a/pkgs/charm/src/mapped.luau +++ b/pkgs/charm/src/mapped.luau @@ -32,14 +32,18 @@ local function mapped(selector: () -> { [KI]: VI }, mapper: (ite local previousData = currentData currentData = selector() - for key, cachedKey in keyCache do + for key in previousData do if currentData[key] ~= nil then continue end - currentOutput = ensureCanMutateOutput(currentOutput, previousOutput) - currentOutput[cachedKey] = nil - keyCache[key] = nil + local cachedKey = keyCache[key] + + if cachedKey then + currentOutput = ensureCanMutateOutput(currentOutput, previousOutput) + currentOutput[cachedKey] = nil + keyCache[key] = nil + end end for key, value in currentData do diff --git a/pkgs/charm/tests/mapped.spec.luau b/pkgs/charm/tests/mapped.spec.luau index be2821c..7bc4a0c 100644 --- a/pkgs/charm/tests/mapped.spec.luau +++ b/pkgs/charm/tests/mapped.spec.luau @@ -52,6 +52,7 @@ test("should not update if no values change", function() src({ 4, 5, 6, 7 }) src({ 1, 2, 3 }) + map() assert(calls == 3, "should not map unchanged values") assert(table.concat(map()) == "234", table.concat(map())) assert(prev == map(), "should not create new table")