ReactiveX / rxjs

A reactive programming library for JavaScript
https://rxjs.dev
Apache License 2.0
30.81k stars 3.01k forks source link

innerFrom treats anything with "length" property as an array, even if this anything has iterable implemented #7497

Open aweppc opened 2 months ago

aweppc commented 2 months ago

Describe the bug

Hello! I've encountered an error in rxjs published as latest (7.8.1 as of writing this)

I've built a simple iterable structure for a specific task. It also had a length property, since I needed to check for that in my operator function.

When I've put that iterable object into from, it did nothing. Some digging showed up that innerFrom treats anything with length property as array just by having that said property and not being a function.

Either isArrayLike should be changed in some way to fit the fromArrayLike or order of checks should be different, so that iterables that are not arrays, but have length property, would be treated as iterables

Expected behavior

from({ [Symbol.iterable](): { ... }, get length() { ... } }) should treat argument as iterable

Reproduction code

import './style.css';

import { from } from 'rxjs';

export class Example<T> implements Iterable<T> {
  private items: T[] = [];

  public add(item: T) {
    this.items.push(item);
  }

  // comment this getter out to see the difference
  public get length() {
    return this.items.length;
  }

  private *generator() {
    for (let i = 0; i < this.items.length; i++) {
      yield this.items[i];
    }
  }

  [Symbol.iterator](): Iterator<T, any, undefined> {
    return this.generator();
  }
}

const queue = new Example<string>();
queue.add('kek');
queue.add('lol');
queue.add('wut');
for (const value of queue) {
  console.log(value);
}
from(queue).subscribe((value) => console.log(value));
// look at the console
// the "for" loop logs values correctly
// while observable thing does that only if "length" getter is commented out


### Reproduction URL

https://stackblitz.com/edit/rxjs-gsebx7?file=index.ts

### Version

7.8.1

### Environment

_No response_

### Additional context

_No response_