I have the below function which generates and returns a new function. I'll call the returned function repetatively, and thus wanted to make it become its own function, vs this one just always checking numberOfPlayers first and then doing the next check. As you can see, the returned function is somewhat repetative. For example, I always have to set newCol to "-2 * column, I already return the same thing for cases 0 and default, And the tuple returned always has the value of newCol as the "column" parameter. Is there any way to "shorten" the code in this function, other than the obvious choice of breaking the internals into three separate methods?
The way it's written now works exactly as expected, it just feels like a code smell when I look at it.
private func generateLoserLocationFunction(numberOfPlayers: Int) -> (column: Int, row: Int) -> (column: Int, row: Int) {
if numberOfPlayers == 8 {
return { row, column in
let newCol = -2 * column
switch column {
case 0:
return (newCol, row / 2)
case 1:
return (newCol, row ^ 1)
default:
return (newCol, 0)
}
}
} else if numberOfPlayers == 16 {
return { row, column in
let newCol = -2 * column
switch column {
case 0:
return (newCol, row / 2)
case 1:
return (newCol, 3 - row)
case 2:
return (newCol, row ^ 1)
default:
return (newCol, 0)
}
}
} else if numberOfPlayers == 32 {
return { row, column in
let newCol = -2 * column
switch column {
case 0:
return (newCol, row / 2)
case 1:
return (newCol, (row + 4) % 8)
case 2:
return (newCol, row)
case 3:
return (newCol, row ^ 1)
default:
return (newCol, 0)
}
}
} else {
abort()
}
}