Skip to content

Commit

Permalink
Merge pull request #6 from michael-groble/add-geohash-iterator
Browse files Browse the repository at this point in the history
add geohash iterator
  • Loading branch information
michael-groble authored Jan 14, 2017
2 parents f221f32 + f7e17ee commit ffec0ed
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Sources/Geohash/GeohashIterator.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//
// GeohashIterator.swift
// Geohash
//
// Created by michael groble on 1/12/17.
//
//

public class GeohashIterator : IteratorProtocol, Sequence {

let bounds: BoundingBox
var latBaseline: GeohashBits
var current: GeohashBits?

public init(bounds: BoundingBox, bitPrecision: UInt8) throws {
self.bounds = bounds
self.latBaseline = try GeohashBits(location: bounds.min, bitPrecision: bitPrecision)
self.current = self.latBaseline
}

public func next() -> GeohashBits? {
defer { advanceCurrent() }
return current
}

private func advanceCurrent() {
// advance eastward until we are out of the bounds then advance northward
if var bits = self.current {
bits = bits.neighbor(.east)
if bounds.intersects(bits.boundingBox()) {
self.current = bits
}
else {
self.latBaseline = latBaseline.neighbor(.north)
self.current = bounds.intersects(latBaseline.boundingBox()) ? latBaseline : nil
}
}
}
}
40 changes: 40 additions & 0 deletions Tests/GeohashTests/GeohashIteratorTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//
// GeohashIteratorTests.swift
// Geohash
//
// Created by michael groble on 1/12/17.
//
//

import XCTest
@testable import Geohash

class GeohashIteratorTests: XCTestCase {

var bounds: BoundingBox!

override func setUp() {
super.setUp()

self.bounds = try! BoundingBox(
min: Location(longitude: 0.09991, latitude: 51.49996),
max: Location(longitude: 0.10059, latitude: 51.50028)
)
}


func testIterateLevel8() throws {
let subject = try GeohashIterator(bounds: bounds, bitPrecision: 20)
XCTAssertEqual(subject.next()!.hash(), "u10hfr2c")
XCTAssertEqual(subject.next()!.hash(), "u10hfr31")
XCTAssertEqual(subject.next()!.hash(), "u10hfr2f")
XCTAssertEqual(subject.next()!.hash(), "u10hfr34")
XCTAssertNil(subject.next())
}
}

extension GeohashIteratorTests {
static var allTests = [
("testIterateLevel8", testIterateLevel8),
]
}
1 change: 1 addition & 0 deletions Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ import XCTest
XCTMain([
testCase(BoundingBoxTests.allTests),
testCase(GeohashBitsTests.allTests),
testCase(GeohashIteratorTests.allTests),
testCase(LocationTests.allTests),
])

0 comments on commit ffec0ed

Please sign in to comment.