Peter Stuifzand

Broken interface of Math.min

In an article about creating a column layout I found the following two lines of code:

var min = Array.min(blocks);
var index = $.inArray(min, blocks);

This first finds the minimum value in blocks and then the index of that value. This combination of lines is very strange. Array.min already knows the index of the minimum element and throws it away. Then the programmer needs to find the index again with a linear search.

This means the interface of Array.min is incomplete. A more general version would return the index of the value in the array that is minimal. This can’t be written on top of the Array.min function in a efficient manner.

The following is a function that returns the index of the minimum element in elements.

// elements is a non-empty array
function min_index(elements) {
    var i = 1;
    var mi = 0;

    while (i < elements.length) {
        if (elements[i] < elements[mi])
            mi = i;
        i += 1;
    }
    return mi;
}

The corresponding max_index looks like this:

// elements is a non-empty array
function max_index(elements) {
    var i = 1;
    var mi = 0;

    while (i < elements.length) {
        if (!(elements[i] < elements[mi]))
            mi = i;
        i += 1;
    }
    return mi;
}
© 2023 Peter Stuifzand