Jump to content

Simplify this please


roaddog

Recommended Posts

function getColorToImage(arg1, arg2, arg3)
	if (not arg1) then return false end
	if (arg2) then
		if (arg2 == "pink") then return pink end
		if (arg2 == "blue") then return blue end
		if (arg2 == "yellow") then return yellow end
		if (arg2 == "red") then return red end
	end
	if (arg1 == "pink") then return pink_1 end
	if (arg1 == "blue") then return blue_1 end
	if (arg1 == "yellow") then return yellow_1 end
	if (arg1 == "red") then return red_1 end
	if (arg3 == "pink") then return pink_2 end
	if (arg3 == "blue") then return blue_2 end
	if (arg3 == "yellow") then return yellow_2 end
	if (arg3 == "red") then return red_2 end
end

could you make it simpler?

Link to comment
local arg1Colors = {
  ["pink"] = pink_1,
  ["blue"] = blue_1,
  ["yellow"] = yellow_1,
  ["red"] = red_1
}

local arg2Colors = {
  ["pink"] = pink,
  ["blue"] = blue,
  ["yellow"] = yellow,
  ["red"] = red
}

local arg3Colors = {
  ["pink"] = pink_2,
  ["blue"] = blue_2,
  ["yellow"] = yellow_2,
  ["red"] = red_2
}

function getColorToImage(arg1, arg2, arg3)
  -- dont check anything if arg1 is nil
  if (not arg1) then return false end
  
  -- return with nil-coalescing 'or' functionality in order of arg2, then arg1 and lastly arg3
  return arg2Colors[arg2] or arg1Colors[arg1] or arg3Colors[arg3] or nil
end

This is one way of simplifying the function, a tiny bit more readable and maintainable, but still unfortunately cryptic with these argument names.

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...