Partial sorting API

Rough draft: GitHub - LiviaMedeiros/proposal-partial-sort: Proposal for partial sort API in JavaScript · GitHub

This proposes adding new method Array.p.top(k, compareFn) that efficiently combines sorting and selecting by skipping unnecessary sorting iterations. It would also look great on Iterator.prototype, allowing sorting to be lazy.

The closest prior ideas i found are array.prototype.winner and Iterator.prototype.findMin, Iterator.prototype.findMax methods which for this proposal are special case where k === 1.

The name is definitely subject to bikeshedding. :)

I'd love to get some feedback if there's any chance to add such method, before moving forward with polyfill and more formal definition.

iter-tools already has an implementation!

I would pretty strongly recommend using iter-tools instead of the browser-native helpers, as the browser native helpers think an iterator is an instance of a particular class (OO-style), while iter tools treats iterators as a decentralized protocol (FP-style).

1 Like

As much as I personally love stuff like this, for it to get through committee there would need to be compelling use cases presented.

Concrete use cases worth putting in the proposal: top-k search results, leaderboards, and streaming logs where only the best N matter and a full sort is wasteful. Even with iter-tools available, a native method standardizes semantics across libraries and avoids a dependency. For committee feedback, show benchmarks against sort().slice(0, k) on large arrays and demonstrate the lazy iterator benefit; that directly addresses the 'compelling use cases' bar.

Yep, that is why iter-tools added it.

Then again, iter-tools makes a huge effort to have a stated philosophy, to refine it, and to justify our decisions in terms of it

For us it was enough that the memory usage would, for some people, be the difference between a tool that worked and one that did not.

Sorting the whole Array requires 2N memory (!!!!!!)

A heap of ten items requires 10 memory.

TC39 has no such philosophical work ethic.

It does not explain its principles. As far as I can tell it does not ever seem to take initiative for reasons of principle. That may stem from being voiceless. If I could shut down the in-person TC39 meetings forever, today, I would in a heartbeat.

I mean, I am more or less the principal language designer for the next version of Javascript and I have no standing. I'm not allowed to even address the people who (formally) decide.

Since it seems impossible to me to work with the committee and I refuse to slow down and sacrifice rigor for them, I have decided instead to go around the committe and directly take ownership of all the work they can't or won't do.

It's the ONLY way I can have the bar for quality set as high as I want it. They simply have no interest in setting the bar as high as I want it set. The higher I build my pile of improvements, the greater the risk I pose to TC39's central authority.

Right now I've re-unified XML and HTML into CSTML (just as they were once unified in XHTML).

At the same time I've built the most user-demanded features of all: native JSX web components, and even bigger a way to run TS syntax sugar (and any syntax sugar) without a precompile step.

That's a pretty harsh and wildly false comment about TC39, and "addressing the people who decide" is what every post in this discourse does.

Separately, please mind our Code of Conduct, and refrain from making personal attacks (which includes attacks against the collective persons in the committee).

I don't see being a whistleblower as an attack on the collective.

Thanks for the feedback!

@ iter-tools: that's cool. I used the __takeSorted for benchmark comparison, mentioned below.
To answer it from "why do we need this in ES rather than in userland library" angle, the main purpose of proposed method is improving performance, and we should probably expect native implementations to be faster and less memory-hungry than userland implementation. It's also quite counter-intuitive that native sorting is slower and takes more RAM, and proper implementation is far from ad hoc three-liner.
Not sure how the second message is relevant here.

@ use cases: added GitHub - LiviaMedeiros/proposal-partial-sort: Proposal for partial sort API in JavaScript · GitHub mentioning some. The .sort().slice() pattern appear quite a lot in the wild.

@ native method benefits: i'll try to come up with additional section mentioning that native implementation is better and why it can not be implemented natively without introducing new method as engine-side optimization (shortly, engine can't simply replace .toSorted().slice() with partial sort because .toSorted()'s operations are observable, e.g. if array is a proxy and/or compareFn has side effects).

@ benchmarks: I drafted a very rough polyfill for this and measured it against iter-tools.__takeSorted and .sort().slice(). On large arrays polyfill is significantly faster.

Not sure how to demonstrate benefits in terms of memory, aside from theoretical part (obviously .toSorted() builds N-sized array while .top() builds k-sized, this is already mentioned in Solution section of proposal) and edge case snippets (partially sorting generator that returns 10e10 elements would run compareFn 10e10 times and keep k elements, full sort will run into OOM).
It's probably feasible to measure using process.memoryUsage() and collect some numbers, but IMHO it's also trivial to imagine the algorithm with k=1 consuming infinite iterator and never holding more than k+1 elements in memory. While Array.prototype.sort.call({length:Number.MAX_SAFE_INTEGER}) instantly and unconditionally OOMs.

Let me know if there's anything else that can be improved to move this proposal forward, or if there's any unavoidable obstacle that would block it.