Skip to content

fix(takeLast): prevent RangeError when count is Infinity#7608

Open
JSap0914 wants to merge 1 commit into
ReactiveX:masterfrom
JSap0914:fix/takeLast-infinity-rangeerror
Open

fix(takeLast): prevent RangeError when count is Infinity#7608
JSap0914 wants to merge 1 commit into
ReactiveX:masterfrom
JSap0914:fix/takeLast-infinity-rangeerror

Conversation

@JSap0914

Copy link
Copy Markdown

Problem

takeLast(Infinity) throws a RangeError: Invalid array length at subscription time:

// Throws: RangeError: Invalid array length
of(1, 2, 3).pipe(takeLast(Infinity)).subscribe(console.log);

The cause is line 50 of takeLast.ts:

let ring = new Array<T>(count);  // new Array(Infinity) → RangeError

JavaScript forbids creating an array with a non-integer or infinite length argument.

Fix

Use a growable array ([]) when count is non-finite. The ring-buffer index arithmetic already handles Infinity correctly because n % Infinity === n for every finite n, so no further changes to the logic are required:

let ring: T[] = isFinite(count) ? new Array<T>(count) : [];

After the fix, takeLast(Infinity) behaves like takeLast(n) where n >= source.length: it buffers every value and emits them all on completion.

Tests

Two new tests added to takeLast-spec.ts:

  • Synchronous assertion that no error is thrown and all values are emitted
  • Marble test verifying the observable shape matches the source

This fix was developed with AI assistance.

`takeLast(Infinity)` threw `RangeError: Invalid array length` because
`new Array(Infinity)` is not a valid JavaScript expression.

Fix by conditionally allocating the ring buffer only when count is finite.
For non-finite counts the operator falls back to a growable array. The
ring-buffer index arithmetic already handles this correctly since
`n % Infinity === n` for all finite n, so no further changes are needed.

Fixes: https://github.com/ReactiveX/rxjs/issues/XXXX
Copilot AI review requested due to automatic review settings June 23, 2026 04:46

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@ajafff

ajafff commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

IMO takeLast(Infinity) should be equal to identity, i.e. not changing the source sequence at all, so it needs no buffer.

On the other hand that would change the existing behavior of only emitting the items on complete to emitting immediately...

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.

3 participants