Skip to content

Commit

Permalink
fix: increment and decrement edge case (#11506)
Browse files Browse the repository at this point in the history
* fix: increment and decrement edge case

* fix/simplify test

* simplify

* Apply suggestions from code review

* golf

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
Co-authored-by: Rich Harris <hello@rich-harris.dev>
  • Loading branch information
3 people committed May 7, 2024
1 parent 8318b3d commit 0cf6d56
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-seas-jog.md
@@ -0,0 +1,5 @@
---
"svelte": patch
---

fix: coerce incremented/decremented sources
6 changes: 2 additions & 4 deletions packages/svelte/src/internal/client/runtime.js
Expand Up @@ -1011,7 +1011,7 @@ function get_parent_context(component_context) {
* @returns {number}
*/
export function update(signal, d = 1) {
const value = get(signal);
var value = +get(signal);
set(signal, value + d);
return value;
}
Expand All @@ -1022,9 +1022,7 @@ export function update(signal, d = 1) {
* @returns {number}
*/
export function update_pre(signal, d = 1) {
const value = get(signal) + d;
set(signal, value);
return value;
return set(signal, +get(signal) + d);
}

/**
Expand Down
@@ -0,0 +1,24 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
html: `
<button>update</button>
<p>0, 0, 0, 0</p>
`,

test({ target, assert, logs }) {
const btn = target.querySelector('button');
flushSync(() => btn?.click());

assert.htmlEqual(
target.innerHTML,
`
<button>update</button>
<p>1, -1, 1, -1</p>
`
);

assert.deepEqual(logs, [0, 0, 1, -1]);
}
});
@@ -0,0 +1,20 @@
<script>
let a = $state("0");
let b = $state("0");
let c = $state("0");
let d = $state("0");
function update() {
// @ts-expect-error
console.log(a++);
// @ts-expect-error
console.log(b--);
// @ts-expect-error
console.log(++c);
// @ts-expect-error
console.log(--d);
}
</script>

<button onclick={update}>update</button>
<p>{a}, {b}, {c}, {d}</p>

0 comments on commit 0cf6d56

Please sign in to comment.