I am doing an image drawing and rendering library, and would like some feedback on this code, it simply draws a line in any direction.

The equation for that is:

m = (y2 – y1) / (x2 – x1)

b = y1 – m * x1

y = mx + b

It works but all these if statements are bothering me, and I am not sure if it’s the best solution.

`proc line*(img: var Image, x1, y1, x2, y2: int) = # Necessary pass the values to variables so we can manipulate them var a1 = x1 a2 = x2 b1 = y1 b2 = y2 # To draw correctly we need to iterate over the longest axis if abs(a1 - a2) > abs(b1 - b2): swap(a1, b1) swap(a2, b2) # ¹ To make sure we are iterating from the lower to the higher if b1 > b2: swap(a1, a2) swap(b1, b2) let m = (a2 - a1) / (b2 - b1) let s = float(a1) - m * float(b1) # ¹ Since we swiped the axis we need to swap x and y if abs(x1 - x2) > abs(y1 - y2): for b in b1..b2: let a = float(b) * m + s img.pixel(b, toInt(a), img.strokeColor) else: for b in b1..b2: let a = float(b) * m + s img.pixel(toInt(a), b, img.strokeColor) `