Skip to content

Instantly share code, notes, and snippets.

@rzvl
Last active March 20, 2022 22:21
Show Gist options
  • Save rzvl/048036bf128bc318a46fc460984c12dc to your computer and use it in GitHub Desktop.
Save rzvl/048036bf128bc318a46fc460984c12dc to your computer and use it in GitHub Desktop.
Remove an element by shifting
contract Array {
uint[] arr;
function remove(uint _index) private {
require(_index < arr.length, "index out of bound");
for (uint i = _index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr.pop();
}
function test() external {
arr = [1, 2, 3, 4, 5];
remove(2); // [1, 2, 4, 5]
assert(arr[0] == 1);
assert(arr[1] == 2);
assert(arr[2] == 4);
assert(arr[3] == 5);
assert(arr.length == 4);
arr = [1];
remove(0);
assert(arr.length == 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment