Skip to content

Instantly share code, notes, and snippets.

@pgherveou
Last active April 9, 2019 02:55
Show Gist options
  • Save pgherveou/8e2b3a718bc9e367efa0 to your computer and use it in GitHub Desktop.
Save pgherveou/8e2b3a718bc9e367efa0 to your computer and use it in GitHub Desktop.
/// custom unique identifier
/// @see https://www.firebase.com/blog/2015-02-11-firebase-unique-identifiers.html
private let ASC_CHARS = Array("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz")
private let DESC_CHARS = ASC_CHARS.reverse()
private var lastPushTime: UInt64 = 0
private var lastRandChars = Array<Int>(count: 12, repeatedValue: 0)
func generatePushID(ascending: Bool = true) -> String {
let PUSH_CHARS = ascending ? ASC_CHARS: DESC_CHARS
var timeStampChars = Array<Character>(count: 8, repeatedValue: PUSH_CHARS.first!)
var now = UInt64(NSDate().timeIntervalSince1970 * 1000)
let duplicateTime = (now == lastPushTime)
lastPushTime = now
for var i = 7; i >= 0; i-- {
timeStampChars[i] = PUSH_CHARS[Int(now % 64)]
now >>= 6
}
assert(now == 0, "We should have converted the entire timestamp.")
var id: String = String(timeStampChars)
if !duplicateTime {
for i in 0..<12 { lastRandChars[i] = Int(64 * Double(rand()) / Double(RAND_MAX)) }
} else {
var i: Int
for i = 11; i >= 0 && lastRandChars[i] == 63; i-- {
lastRandChars[i] = 0
}
lastRandChars[i]++
}
for i in 0..<12 { id.append(PUSH_CHARS[lastRandChars[i]]) }
assert(count(id) == 20, "Length should be 20.")
return id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment