Looping in Solidity
In solidity, mapping is very useful to store token value of an address. We have seen it in many contracts and they are normally defined this way:
mapping (address => uint) public users;
Since the mapping is public, we get a free getter and we can get the value of myAddress by using a simple
users(myAddress);
Solidity mapping might look similar to an associative array at first glance but its not. It doesn’t have indices, making it hard to loop through all addresses. It is still possible though but not straight forward.
Arrays are much easier to manage,
address[] public addressIndices;// start adding address in array
addressIndices.push(newAddress);
...// We know the length of the array
uint arrayLength = addressIndices.length;for (uint i=0; i<arrayLength; i++) {
// do something
}
Let’s say we want to calculate the total value of all addresses, having an array of addresses can really be helpful.
mapping (address => uint) public mappedUsers;
address[] public addressIndices;// start adding address in array
addressIndices.push(newAddress);// define mappedUsers as well
mappedUsers[newAddress] = someValue;
...// We know the length of the array
uint arrayLength = addressIndices.length;// totalValue auto init to 0
uint totalValue;for (uint i=0; i<arrayLength; i++) {
totalValue += mappedUsers[addressIndices[i]];
}
What if we want to delete the array efficiently? We have to move the array’s last position to the deleted position.
uint indexToBeDeleted;
mapping (address => uint) public mappedUsers;
address[] public addressIndices;
uint arrayLength = addressIndices.length;for (uint i=0; i<arrayLength; i++) {
if (addressIndices[i] == addressToBeDeleted) {
indexToBeDeleted = i;
break;
}
}// if index to be deleted is not the last index, swap position.
if (indexToBeDeleted < arrayLength-1) {
mappedUsers[indexToBeDeleted] = mappedUsers[arrayLength-1];
}
// we can now reduce the array length by 1
addressIndices--;
Referring to the code above, assuming we don’t want a for-loop to look for the index of the address to be deleted, we need to record the index of the item in a struct. It gets a bit more complicated if we want to do a proper CRUD.
A sample of the full code might look something like this.
Happy coding!