Skip to content

Instantly share code, notes, and snippets.

@asselstine
Created November 1, 2018 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asselstine/47f90ca7911a951eac05c60d64f1f765 to your computer and use it in GitHub Desktop.
Save asselstine/47f90ca7911a951eac05c60d64f1f765 to your computer and use it in GitHub Desktop.
Adds the ability to remove an address directly from an array
pragma solidity ^0.4.24;
library IndexedAddressArray {
struct Data {
address[] addresses;
mapping(address => uint256) indices;
}
function pushAddress(Data storage self, address _value) internal returns (uint256) {
uint256 index = self.addresses.push(_value) - 1;
self.indices[_value] = index;
return index;
}
function removeAddress(Data storage self, address _value) internal {
uint256 index = self.indices[_value];
delete self.indices[_value];
uint256 lastIndex = self.addresses.length - 1;
if (index != lastIndex) {
address lastValue = self.addresses[lastIndex];
self.addresses[index] = lastValue;
self.indices[lastValue] = index;
}
self.addresses.length--;
}
function hasAddress(Data storage self, address _value) internal returns (bool) {
return self.indices[_value] != 0 ||
(self.addresses.length > 0 && self.addresses[0] == _value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment