array.prototype.winner

Most of the time - at least in my experience, and in all of these examples - you have some way of mapping your inputs to a number, and then you want the thing which produces the highest value. For example, for dates it is just .valueOf(), for "longest name" it is x => x.name.length, etc.

That is, something like

function argmax(iterable, fn) {
  let max, best;
  let first = true;
  for (let val of iterable) {
    let candidate = fn(val);
    if (first || candidate > max) {
      max = candidate;
      best = val;
      first = false;
    }
  }
  if (first) throw new TypeError('empty collection');
  return best;
}

I've named it argmax here because that's what this function is named in mathematics, though unfortunately Pytorch uses argmax to mean something slightly different.

That's a slightly different thing than you're asking for, and strictly speaking is less powerful (sometimes we have a way of comparing things but no good way of mapping them to values on a scale), but it's usually more convenient when we do have such a mapping (especially if the mapping is expensive to compute, in which case we'd need to do caching for our comparator).

Anyway for names I'd probably go with Iterator.prototype.max or .maxBy (for the comparator-taking and mapping-function-taking versions respectively).

I've wanted to propose something like this for a while and may yet get around to someday, though I haven't had much time lately.

1 Like

It also implies that there is some area of uncertainty of the outcome for the viewer, depending on how the rules are, however, in our case, the rules are simpler than that.

I mean, plenty of mathematical operations that can be performed on primitive values, make sense to and commonly are performed on collections of similar data.

To make a proposal, I assume there may be some gaps left to fill out; perhaps some that I could help with. What would move this topic forwards?

The main useful things at this stage are 1) collecting several minimally-contrived examples of cases where you'd want this ("longest name" is a bit contrived, but "oldest" is more reasonable, e.g.) and documenting the various ways one could do this currently (a .reduce, a for loop, etc) and 2) collecting prior art from other languages (how would you do this in Python, C++, etc).

Continuing this. I think a name like .findBest or just .best would be more fitting