Skip to content

fix(arrayMethods): convert slice indices like Array.prototype.slice - #1376

Open
Taiwudao wants to merge 1 commit into
immerjs:mainfrom
Taiwudao:fix/array-methods-slice-index
Open

Taiwudao wants to merge 1 commit into
immerjs:mainfrom
Taiwudao:fix/array-methods-slice-index

Conversation

@Taiwudao

Copy link
Copy Markdown

Problem

enableArrayMethods() overrides slice with an optimized implementation. The helper that normalizes the start and end arguments only clamps them to the array bounds:

function normalizeSliceIndex(index: number, length: number): number {
	if (index < 0) {
		return Math.max(length + index, 0)
	}
	return Math.min(index, length)
}

The specification applies ToIntegerOrInfinity before clamping. As a result, non-integer and non-numeric arguments are interpreted differently from native slice and from Immer without the plugin:

  • slice(NaN) returns [] instead of the whole array.
  • slice(1.5) returns [undefined, undefined, undefined] for [1, 2, 3, 4] instead of [2, 3, 4].
  • slice(-1.5) returns two undefined entries instead of [4].
  • slice(0.5, 3.5) returns [undefined, undefined, undefined] instead of [1, 2, 3].

The same helper is used for the splice start index, so this also corrects the insertion index used for cross-reference handling there.

Fix

I added a toIntegerOrInfinity helper and used it inside normalizeSliceIndex. Number.isNaN and Math.trunc mirror the specification conversion, and unary + keeps the native TypeError for symbols.

This does not change the existing explicit null end behavior; that case is covered separately by #1321.

Tests

Added __tests__/array-methods-slice-index.js, which runs the same argument matrix with the plugin on and off and with autoFreeze on and off. It covers NaN, positive and negative fractions, numeric strings, and infinities.

npx vitest run __tests__/array-methods-slice-index.js

Result: 44 passed (44).

The full suite passes: 4257 passed, 8 skipped. Reverting the source change makes 12 of the new tests fail, for example slice(-1.5) yields [undefined, undefined] instead of [4], and the standalone reproduction reports 6 of 11 cases differing from native slice.

Notes

This is plugin-only: the unoptimized path already matches native slice. I could not find an existing issue for this exact argument coercion case, so the report here is based on a direct comparison between the plugin, the unoptimized path, and native slice.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant