chalup/advent-swift

Consider extending types instead of adding free functions

Closed this issue · 0 comments

ayoy commented

func manhattanDistance(_ a: Point, _ b: Point) -> Int {

This is a matter of taste, because there are people that prefer free functions for everything.
You could rewrite that function like this:

extension Point {
    func manhattanDistance(to other: Point) -> Int {
        return abs(x - other.x) + abs(y - other.y)
    }
}

and use it like this:

let p = Point(x: 0, y: 0)
let q = Point(x: 1, y: 1)
print(p.manhattanDistance(to: q)) // "2"

Since you're using manhattanDistance function in a call to map (that takes a closure), you could do another trick and define a function that returns a closure, like this:

func manhattanDistance(to other: Point) -> (Point) -> Int {
    return { point in
        abs(point.x - other.x) + abs(point.y - other.y)
    }
}

and then:

wiresCrossings(wires: wires)
    .map(manhattanDistance(to: origin))
    .min()!

Just saying :)