Is there any function similar to Python's max(a, b) in Solidity, to find the maximum value between several given?

Viewed 1791

Of course, it could be done via conditionals but I would like to know if there is a more straight-forward approach.

If there isnt any explicit way, what would be the optimal way to implement it?

1 Answers

In the current version 0.8, there's no native function to get a min/max value from a set of input numbers.

For a static number of values, you could implement a simple condition (or a set of conditions if there's more than 2 values):

function max(uint256 a, uint256 b) external pure returns (uint256) {
    return a >= b ? a : b;
}

For a dynamic number of values, you can simply loop through the input array and keep track of the smallest/largest value:

function max(uint256[] memory numbers) external pure returns (uint256) {
    require(numbers.length > 0); // throw an exception if the condition is not met
    uint256 maxNumber; // default 0, the lowest value of `uint256`

    for (uint256 i = 0; i < numbers.length; i++) {
        if (numbers[i] > maxNumber) {
            maxNumber = numbers[i];
        }
    }

    return maxNumber;
}

This functions has a linear complexity. Read-only calls are gas free, but mind the complexity if you're executing the max() from another function as a result of a transaction (that cost gas fees).

Related