Instantly share code, notes, and snippets.

Embed
What would you like to do?
Second attempt at snapping to angle intervals in Trgnmtry. This one works, and runs in linear time.
extension String {
func indexOfClosestSorted(toValue value: Degree) -> Int {
var smallestDifference = last!
var closestIntervalAngleIdx = 0
for i in 0 ..< count {
let closestValueCandidate = self[i]
var difference = fabs(closestValueCandidate - value)
if difference == 0 {
return i
}
if difference < 0 {
difference *= -1
}
if difference < smallestDifference {
smallestDifference = difference
closestIntervalAngleIdx = i
}
}
return closestIntervalAngleIdx
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment