Skip to content

Commit fb879dd

Browse files
authored
fix: ensure $state.snapshot clones holey arrays correctly (#14657)
* fix: ensure $state.snapshot clones holey arrays correctly * fix: ensure $state.snapshot clones holey arrays correctly * fix: ensure $state.snapshot clones holey arrays correctly * fix: ensure $state.snapshot clones holey arrays correctly
1 parent ab1f7f4 commit fb879dd

File tree

4 files changed

+28
-5
lines changed

4 files changed

+28
-5
lines changed

.changeset/clean-bobcats-fail.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: ensure $state.snapshot clones holey arrays correctly

packages/svelte/src/internal/shared/clone.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,30 +54,33 @@ export function snapshot(value, skip_warning = false) {
5454
*/
5555
function clone(value, cloned, path, paths, original = null) {
5656
if (typeof value === 'object' && value !== null) {
57-
const unwrapped = cloned.get(value);
57+
var unwrapped = cloned.get(value);
5858
if (unwrapped !== undefined) return unwrapped;
5959

6060
if (value instanceof Map) return /** @type {Snapshot<T>} */ (new Map(value));
6161
if (value instanceof Set) return /** @type {Snapshot<T>} */ (new Set(value));
6262

6363
if (is_array(value)) {
64-
const copy = /** @type {Snapshot<any>} */ ([]);
64+
var copy = /** @type {Snapshot<any>} */ (Array(value.length));
6565
cloned.set(value, copy);
6666

6767
if (original !== null) {
6868
cloned.set(original, copy);
6969
}
7070

71-
for (let i = 0; i < value.length; i += 1) {
72-
copy.push(clone(value[i], cloned, DEV ? `${path}[${i}]` : path, paths));
71+
for (var i = 0; i < value.length; i += 1) {
72+
var element = value[i];
73+
if (i in value) {
74+
copy[i] = clone(element, cloned, DEV ? `${path}[${i}]` : path, paths);
75+
}
7376
}
7477

7578
return copy;
7679
}
7780

7881
if (get_prototype_of(value) === object_prototype) {
7982
/** @type {Snapshot<any>} */
80-
const copy = {};
83+
copy = {};
8184
cloned.set(value, copy);
8285

8386
if (original !== null) {
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { test } from '../../test';
2+
3+
export default test({
4+
html: `<div>false</div><div>true</div>`
5+
});
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<script>
2+
let arr = []
3+
arr[5] = true
4+
5+
let state = $state([])
6+
state[5] = true
7+
</script>
8+
9+
<div>{2 in $state.snapshot(state)}</div>
10+
<div>{5 in $state.snapshot(state)}</div>

0 commit comments

Comments
 (0)