Splicing an Array in Fuze
-
EDIT: When it is live, check out the code via project id: X7R53MND1Z (the code in this post is copied manually by typing), also the project will show a small example on how you can write automated unit tests for your code (to see if changes break stuff).
I wrote this function to splice an Array in Fuze. Here to share it, in case it's useful to anybody. It's not perfect, feel free to improve it :)
// Download project ID X7R53MND1Z for latest code including unit tests. struct SPLICE_OUTPUT array result[0] array removed[0] endstruct function splice(initialElements, startIndex, removeAmount, addElements) SPLICE_OUTPUT output = [ .result = [], .removed = [] ] int resultIndex = 0 int removedIndex = 0 int addIndex int i int initialLen = len(initialElements) if initialLen == 0 and startIndex == 0 then output.result = addElements endif for i = 0 to initialLen loop if i < startIndex or i >= startIndex + removeAmount then output.result[resultIndex] = initalElements[i] resultIndex += 1 else output.removed[removedIndex] = initialElements[i] removedIndex += 1 endif if i == startIndex then for addIndex = 0 to len(addElements) loop output.result[resultIndex] = addElements[addIndex] resultIndex += 1 repeat endif repeat return output
initialElements: the
array
you wish to splice
startIndex theint
describing the first index from where items should be removed and/or added
removeAmount theint
amount of elements to remove (should be 0 or more) from the array starting atstartIndex
newElements anarray
of elements that should be inserted in the result atstartIndex
The function returns a structure/object with the following properties:
.result the spliced array
.removed the elements that where removedSo you could use this function in the following way:
arr = [2,4,6,8,10, 12, 14, 16] output = splice(arr, 2, 3, [3,5,7]) n = "\n" print("input: ", arr, n, "result: ", output.result, n, "removed: ", output.removed)
print would output the following:
input: [ 2, 4, 6, 8, 10, 12, 14, 16] result: [ 2, 4, 3, 5, 7, 12, 14, 16] removed: [ 6, 8 , 10]