Skip to content

Instantly share code, notes, and snippets.

@rumkin
Created June 2, 2020 15:11
Show Gist options
  • Save rumkin/9b4695b8207a2b876d15ca0933cbbf5d to your computer and use it in GitHub Desktop.
Save rumkin/9b4695b8207a2b876d15ca0933cbbf5d to your computer and use it in GitHub Desktop.
Lists example
pragma solidity ^0.6.0;
contract Lists {
mapping(uint => uint[]) public list;
function add(uint id, uint value)
public
{
list[id].push(value);
}
function get(uint id, uint index)
public
view
returns(uint)
{
return list[id][index];
}
function count(uint id)
public
view
returns(uint)
{
return list[id].length;
}
function sliceItems(uint id, uint offset, uint limit)
public
view
returns(uint[] memory)
{
uint diff = limit - offset;
uint[] memory result = new uint[](diff);
for (uint i = 0; i < diff; i++) {
result[i] = list[id][offset + i];
}
return result;
}
function callSlice(uint id)
public
view
returns (uint[] memory)
{
uint length = count(id);
return sliceItems(id, 0, length);
}
function callList(uint id)
public
view
returns (uint[] memory)
{
uint length = count(id);
uint[] memory result = new uint[](length);
for (uint i = 0; i < length; i++) {
result[i] = get(id, i);
}
return result;
}
}
contract RemoteList {
Lists public remote;
constructor(address _remote) public {
require(_remote != address(0), 'remote_exists');
remote = Lists(_remote);
}
function callSlice(uint id)
public
view
returns(uint[] memory)
{
uint length = remote.count(id);
return remote.sliceItems(id, 0, length);
}
function callList(uint id)
public
view
returns(uint[] memory)
{
uint length = remote.count(id);
uint[] memory result = new uint[](length);
for (uint i = 0; i < length; i++) {
result[i] = remote.get(id, i);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment