Last active
March 20, 2022 22:21
-
-
Save rzvl/048036bf128bc318a46fc460984c12dc to your computer and use it in GitHub Desktop.
Remove an element by shifting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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