Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Prevent $state bigints incrementing and decrementing from throwing #14485

Merged
merged 11 commits into from
Dec 1, 2024
Merged
5 changes: 5 additions & 0 deletions .changeset/young-beds-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: correctly increment/decrement bigints
25 changes: 17 additions & 8 deletions packages/svelte/src/internal/client/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -984,23 +984,32 @@ function get_parent_context(component_context) {
}

/**
* @param {Value<number>} signal
* @template {number | bigint} T
* @param {Value<T>} signal
* @param {1 | -1} [d]
* @returns {number}
* @returns {T}
*/
export function update(signal, d = 1) {
var value = +get(signal);
set(signal, value + d);
return value;
var value = get(signal);
var result = d === 1 ? value++ : value--;

set(signal, value);

// @ts-expect-error
return result;
}

/**
* @param {Value<number>} signal
* @template {number | bigint} T
* @param {Value<T>} signal
* @param {1 | -1} [d]
* @returns {number}
* @returns {T}
*/
export function update_pre(signal, d = 1) {
return set(signal, +get(signal) + d);
var value = get(signal);

// @ts-expect-error
return set(signal, d === 1 ? ++value : --value);
}

/**
Expand Down
16 changes: 16 additions & 0 deletions packages/svelte/tests/signals/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,4 +765,20 @@ describe('signals', () => {
assert.deepEqual(a.deriveds, null);
};
});

test('bigint states update correctly', () => {
return () => {
const count = state(0n);

assert.doesNotThrow(() => $.update(count));
assert.equal($.get(count), 1n);
assert.doesNotThrow(() => $.update(count, -1));
assert.equal($.get(count), 0n);

assert.doesNotThrow(() => $.update_pre(count));
assert.equal($.get(count), 1n);
assert.doesNotThrow(() => $.update_pre(count, -1));
assert.equal($.get(count), 0n);
};
});
});