Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Min/max index? Min/max element? #11

Closed
mbostock opened this issue Oct 21, 2015 · 2 comments
Closed

Min/max index? Min/max element? #11

mbostock opened this issue Oct 21, 2015 · 2 comments

Comments

@mbostock
Copy link
Member

Related d3/d3#1964.

Currently, min and max return the minimum and maximum value from an array of elements, using an optional value accessor.

In some cases, it might be nice to either return the minimum or maximum index of a given element, or the element itself. For example:

var array = [{foo: 42}, {foo: 91}];
min(array, function(d) { return d.foo; }); // 42
minIndex(array, function(d) { return d.foo; }); // 0
minElement(array, function(d) { return d.foo; }); // {foo: 42}

Protovis supported functionality similar to this with pv.min.index and pv.max.index. Perhaps it’d be sufficient to support just the minimum and maximum index, since that could be used to extract the element.

@mbostock
Copy link
Member Author

mbostock commented Dec 2, 2015

Another thought is a “scan” method that takes a comparator and returns the index of the least element according to the comparator. Sort of like bisect, but in linear time for unsorted arrays.

var array = [{foo: 42}, {foo: 91}];
scan(array, function(a, b) { return a.foo - b.foo; }); // 0
scan(array, function(a, b) { return b.foo - a.foo; }); // 1

@mbostock
Copy link
Member Author

mbostock commented Dec 2, 2015

Heh, I’m caught in a time loop! In d3/d3@0b1b9fb, I removed d3.first and d3.last (see d3/d3#420). The first was implemented as:

function first(array, f) {
  var i = 0, n = array.length, a = array[0], b;
  if (arguments.length === 1) f = ascending;
  while (++i < n) {
    if (f.call(array, a, b = array[i]) > 0) {
      a = b;
    }
  }
  return a;
}

But this returns the first (or last) value, not the index. Also, I don’t see a great reason to have both a first and a last method given that you can just invert the comparator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant