Pagination in Solidity

Simple working Solidity code to paginate arrays returned from a Smart Contract:

pragma solidity >=0.4.22 <0.6.0;

contract ArrayPagination {
    uint[] arr;

    function add(uint data) public {
        arr.push(data);
    }

    function fetchPage(uint cursor, uint howMany) public view returns (uint[] memory valueset, uint newCursor) {
        uint length = howMany;
        if (length > arr.length - cursor) {
            length = arr.length - cursor;
        }

        uint[] memory values = new uint[] (length);
        for (uint i = 0; i < length; i++) {
            values[i] = arr[cursor + i];
        }

        return (values, cursor + length);
    }
}

No comments: