[pshaiCmd] ArrayRemove2

stable
By pshai in Miscellaneous Published May 2020 👁 1,390 views 💬 0 comments

Description

Simple command to remove value(s) from the array. Usage testample:
local testArr1 = {'a', 'a', 'b', 'c', 'a', 'b'}
local testArr2 = {1, 2, 1, 4, 7, 1}

local result1 = CC_ArrayRemove2(testArr1, 'a')
local result2 = CC_ArrayRemove2(testArr2, 1)
local result3 = CC_ArrayRemove2(testArr1, 'a', true)
local result4 = CC_ArrayRemove2(testArr2, 1, true)

Log(result1) -- missing first 'a'
Log(result2) -- missing first '1'
Log(result3) -- missing all 'a'
Log(result4) -- missing all '1'
HaasScript
DefineCommand('ArrayRemove2', 'Removes value(s) from the array')

local input = DefineParameter(ListDynamicType, 'input', 'The array', true, {1, 2, 1, 4, 7, 1})
local value = DefineParameter(DynamicType, 'value', 'Value to be removed from the array.', true, 1)
local loop = DefineParameter(BooleanType, 'loop', 'If this is set to false, will only remove the first found value. If set to true, will remove all values found.', false, false)


if #input == 0 then
    LogError('CC_ArrayRemove2: Array contains no cells!')
end

local remove = function(array, value)
    local index = 1
    for i=1, #array do
        if array[i] == value then
            index = i
            break
        end
    end

    local temp1 = Grab(array, 0, index-1)
    local temp2 = Grab(array, index, #array - index)
    local result

    if #temp1 == 0 then
        result = temp2
    elseif #temp2 == 0 then
        result = temp1
    elseif #temp1 == 0 and #temp2 == 0 then
        result = array
    else
        result = ArrayConcat(temp1, temp2)
    end

    return result
end

local result

if loop then
    result = input
    while ArrayContains(result, value) do
        result = remove(result, value)
    end
else
    result = remove(input, value)
end

DefineOutput(ListDynamicType, result, 'Array')

0 Comments

Sign in to leave a comment.

No comments yet. Be the first!