More concise alternatives to `Iterator.from()`?

Verbose example

Example where using Intl.Segmenter is a bit verbose:

const segmenter = new Intl.Segmenter('en-us', { granularity: 'word' });
const segments = segmenter.segment('How are you?');
console.log(
  Iterator.from(segments).filter(x => x.isWordLike).map(x => x.segment).toArray()
);

Solution 1: Iterator()

Iterator could become callable and behave like Iterator.from():

Iterator(segments).filter(x => x.isWordLike).map(x => x.segment).toArray()
  • Precedent: Object(), Number(), String(), etc. already coerce values.

Solution 2: Object.prototype.values()

Preparation:

Object.prototype.values = function () { return this[Symbol.iterator]() };

Usage:

segments.values().filter(x => x.isWordLike).map(x => x.segment).toArray()

This method could also be called .iter().

Solution 3: %IntlSegmentsPrototype%.values()

segments.values().filter(x => x.isWordLike).map(x => x.segment).toArray()
  • Precedent: Many iterable objects have the method .values() – e.g. instances of Array, Map, Set.
  • Downside: only useful in this context (vs. everywhere the Iterator API is used).

I think iterables should always have a string-keyed name for getting an iterator, as an alias for the Symbol.iterator method. It shouldn't universally be named values - for example, for strings I think we should have codepoints - but I think that's the ideal, rather than trying to make Iterator.from more convenient. That would be a feature request for 402, which they accept as issues.

Note that almost every iterable web API already has .values (in webidl declaring something as iterable automatically adds .values, .keys, and a few others), so it's only a few places in JS which are missing such a method.

Re: solution 2, we are never going to add any new string-keyed properties to Object.prototype under any circumstances.

2 Likes

Thanks! Good points. Strings are indeed the only other case I can think of where I’d use Iterator.from().

I filed an issue: `%IntlSegmentsPrototype%.values()` · Issue #945 · tc39/ecma402 · GitHub

I'm intending to propose .codepoints for strings (or some other name) when I get some time, so hopefully we'll have these all rounded out someday.

1 Like

Great!

(I’m glad we have Iterator methods now. It took me a while to figure out that iterator-first can fit well into JS—seeing Rust’s iteration API finally made it click.)

1 Like