pragma solidity ^0.4.24; contract PaginatedNumbers { uint256[] public squares; constructor() public { for (uint256 _i = 1; _i <= 51; _i++) { squares.push(_i * _i); } } function getPaginatedSquares( uint256 _page, uint256 _resultsPerPage ) external view returns (uint256[]) { /* ex: _page 1, _resultsPerPage 20 | 1 * 20 - 20 = 0 ex2: _page 2, _resultsPerPage 20 | 2 * 20 - 20 = 20 starting point for listing items in array */ uint256 _squareIndex = _resultsPerPage * _page - _resultsPerPage; // return emptry array if already empty or _squareIndex is out of bounds if ( squares.length == 0 || _squareIndex > squares.length - 1 ) { return new uint256[](0); } // need to create fixed length array because we cannot push to array in memory uint256[] memory _squares = new uint256[](_resultsPerPage); // start starting counter for return array uint256 _returnCounter = 0; // loop through array from starting point to end point for ( _squareIndex; // ex _page 2, _resultsPerPage 20 | 2 * 40 _squareIndex < _resultsPerPage * _page; _squareIndex++ ) { /* add array item unless out of bounds if so add uninitialized value (0 in the case of uint256) */ if (_squareIndex < squares.length - 1) { _squares[_returnCounter] = squares[_squareIndex]; } else { _squares[_returnCounter] = 0; } _returnCounter++; } return _squares; } }
0.4.18