Table to color sequence function

Hey! This is a very small resource but one you might find useful.

If you’re ever dealing with hardcoded color sequences, say something like rarities of an item, you might do something similar to:

local rarityColors = {
    Common = {
        Color3.new(1, 1, 1),
        Color3.new(0.6, 0.6, 0.6)
    },
    Uncommon = {
        Color3.new(0.509803, 1, 0.494117),
        Color3.new(0.121568, 1, 0.090196)
    },
    Rare = {
        Color3.new(0.411764, 0.764705, 1),
        Color3.new(0, 0.764705, 1)
    }
}

local colorSequence = ColorSequence.new({
    ColorSequenceKeypoint.new(0, RarityColors[rarity][1]),
    ColorSequenceKeypoint.new(1, RarityColors[rarity][2])
})

It does work but what about for when you have a higher rarity item and you want its color sequence to have more colors or less colors? Well I made this short function to turn any table with colors in it into a color sequence with the correct keypoint positions!

Here it is, and I hope someone else will find it useful as I have:

local Utils = {}

function Utils.TableToClrSeq(table)
    local timePositions = {}
    local colors = {}

    local j = 0 -- j exists because we count top to bottom in the for loop but the index needs to be bottom to top
    local decimal = (10 / (#table - 1)) / 10
    for i = #table, 1, -1 do
        --[[
            If it's the first sequence then set to 0 because 0 is the first position in a color sequence else
            divide 1 by j to get the correct position.
          ]]
        local timePos = if i == #table then 0 else decimal * j
        timePositions[j + 1] = timePos
        j += 1
    end

    -- In case the table is a dictionary we'll use an index and not a for k, v loop
    for i = 1, #table do
        local color = table[i]
        colors[i] = ColorSequenceKeypoint.new(timePositions[i], color)
    end

    return ColorSequence.new(colors)
end

return Utils