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
pull/14652/head
Dominic Gannaway 2 weeks ago committed by GitHub
parent ab1f7f437e
commit fb879dd702
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ensure $state.snapshot clones holey arrays correctly

@ -54,22 +54,25 @@ export function snapshot(value, skip_warning = false) {
*/ */
function clone(value, cloned, path, paths, original = null) { function clone(value, cloned, path, paths, original = null) {
if (typeof value === 'object' && value !== null) { if (typeof value === 'object' && value !== null) {
const unwrapped = cloned.get(value); var unwrapped = cloned.get(value);
if (unwrapped !== undefined) return unwrapped; if (unwrapped !== undefined) return unwrapped;
if (value instanceof Map) return /** @type {Snapshot<T>} */ (new Map(value)); if (value instanceof Map) return /** @type {Snapshot<T>} */ (new Map(value));
if (value instanceof Set) return /** @type {Snapshot<T>} */ (new Set(value)); if (value instanceof Set) return /** @type {Snapshot<T>} */ (new Set(value));
if (is_array(value)) { if (is_array(value)) {
const copy = /** @type {Snapshot<any>} */ ([]); var copy = /** @type {Snapshot<any>} */ (Array(value.length));
cloned.set(value, copy); cloned.set(value, copy);
if (original !== null) { if (original !== null) {
cloned.set(original, copy); cloned.set(original, copy);
} }
for (let i = 0; i < value.length; i += 1) { for (var i = 0; i < value.length; i += 1) {
copy.push(clone(value[i], cloned, DEV ? `${path}[${i}]` : path, paths)); var element = value[i];
if (i in value) {
copy[i] = clone(element, cloned, DEV ? `${path}[${i}]` : path, paths);
}
} }
return copy; return copy;
@ -77,7 +80,7 @@ function clone(value, cloned, path, paths, original = null) {
if (get_prototype_of(value) === object_prototype) { if (get_prototype_of(value) === object_prototype) {
/** @type {Snapshot<any>} */ /** @type {Snapshot<any>} */
const copy = {}; copy = {};
cloned.set(value, copy); cloned.set(value, copy);
if (original !== null) { if (original !== null) {

@ -0,0 +1,5 @@
import { test } from '../../test';
export default test({
html: `<div>false</div><div>true</div>`
});

@ -0,0 +1,10 @@
<script>
let arr = []
arr[5] = true
let state = $state([])
state[5] = true
</script>
<div>{2 in $state.snapshot(state)}</div>
<div>{5 in $state.snapshot(state)}</div>
Loading…
Cancel
Save