Skip to main content

Command Palette

Search for a command to run...

Insert item in middle of roArray

Updated
2 min read

Push and pop are great but what if you need to insert an item in the middle or an array without overwriting the item?

sub main()

    list = [1,2,3,4]
    ' Expectresult: [1,"foo",2,3,4]
    print arrayInsert( list, "middle", 1 ) : printList( list )

    list = [0,1,2,3,4]
    print arrayInsert( list, "first", 0 ): printList( list )

    list = [0,1,2,3,4]
    print arrayInsert( list, "beforeLast", 4 ): printList( list )

    list = [0,1,2,3,4]
    print arrayInsert( list, "last", 5 ): printList( list )

    list = []
    print arrayInsert( list, "empty", 0 ): printList( list )

    list = [0]
    print arrayInsert( list, "at-last", 0 ): printList( list )

    list = [0]
    print arrayInsert( list, "tail", 1 ): printList( list )

    list = [0]
    print arrayInsert( list, "too-high", 2 ): printList( list )

end sub


' This function mutates the list
function arrayInsert( list, newItem, insertIndex% ) as boolean

    ' Index out of bounds
    if insertIndex% < 0 or insertIndex% > list.count() then
        print "Item index out of bounds"
        return false
    end if


    ' List is empty or inserting at last item
    if list.count() = insertIndex% then
        list.push(newItem)
        return true
    end if


    tempList = []

    for i = 0 to list.count() - 1
        if i = insertIndex% then
            tempList.push( newItem )
        end if
        tempList.push(list[i])
    end for

    list.clear()
    list.append(tempList)
    tempList.clear()
    tempList = invalid

    return true

end function

sub printList( list )
    print "[ ";
    for each item in list
        print item; " ";
    end for
    print " ]"
    print
end sub