Skip to content

Commit

Permalink
Add fridgen executable
Browse files Browse the repository at this point in the history
  • Loading branch information
e-kazakov committed Feb 3, 2017
1 parent 9d0abeb commit 389a510
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
5 changes: 4 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import PackageDescription

let package = Package(
name: "frid"
name: "frid",
targets: [
Target(name: "fridgen", dependencies: ["frid"])
]
)
18 changes: 9 additions & 9 deletions Sources/frid.swift → Sources/frid/frid.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@

import Foundation

struct FrId {
public struct FrId {

private init() { }

/// Provides current date. Needed for testing.
internal static var now: () -> Date = { Date() }

/// Fancy ID generator that creates 20-character string identifiers with the following properties:
///
/// 1. They're based on timestamp so that they sort *after* any existing ids.
Expand All @@ -26,25 +26,25 @@ struct FrId {
///
/// - Returns: generated id
public static func generate() -> String {

let nowMilliseconds = UInt64(now().timeIntervalSince1970 * 1000)
defer { lastMilliseconds = nowMilliseconds }

// Convert timestamp to characters from alphabet.
let timeStampChars = (0...7)
.reversed()
.map { (shiftMultiplier: Int) -> UInt64 in nowMilliseconds >> UInt64(6 * shiftMultiplier) }
.map { (rnd: UInt64) -> Int in Int(rnd % 64) }
.map { (index: Int) -> Character in alphabetCharacters[index] }

let duplicateTime = nowMilliseconds == lastMilliseconds
// If the timestamp hasn't changed since last generation, use the same random number, except incremented by 1.
randomCharactersIndexes = duplicateTime ? inc(randomCharactersIndexes) : generateNewRandomIndexes()

let randomCharacters = randomCharactersIndexes.map { alphabetCharacters[$0] }

let idCharacters = timeStampChars + randomCharacters

return String(idCharacters)
}
}
Expand Down
3 changes: 3 additions & 0 deletions Sources/fridgen/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import frid

print(FrId.generate())

0 comments on commit 389a510

Please sign in to comment.