Skip to content

Instantly share code, notes, and snippets.

@nathanborror
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanborror/702a4a195c73f281d28a to your computer and use it in GitHub Desktop.
Save nathanborror/702a4a195c73f281d28a to your computer and use it in GitHub Desktop.
import UIKit
typealias Session = (NSDate, [Int])
let data = [
["created": NSDate(timeIntervalSince1970: 1422600001), "reps": 0],
["created": NSDate(timeIntervalSince1970: 1422600002), "reps": 1],
["created": NSDate(timeIntervalSince1970: 1422600003), "reps": 1],
["created": NSDate(timeIntervalSince1970: 1422700000), "reps": 0],
["created": NSDate(timeIntervalSince1970: 1422700000), "reps": 0],
]
func distinct<T: Equatable>(source: [T]) -> [T] {
var unique = [T]()
for item in source {
if !contains(unique, item) {
unique.append(item)
}
}
return unique
}
func buildIndex(records: [[String: NSObject]]) -> [Session] {
func getDate(date: NSDate) -> NSDate {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let newDate = formatter.stringFromDate(date)
return formatter.dateFromString(newDate)!
}
let dates = distinct(records.map { getDate($0["created"] as NSDate) })
return dates.map { (date) -> Session in
let forDate = records.filter { date == getDate($0["created"] as NSDate) }
return (date, forDate.map { $0["reps"] as Int })
}
}
let days = buildIndex(data)
for (day, reps) in days {
println(day)
for rep in reps {
println(rep)
}
}
import UIKit
typealias Session = (NSDate, [Int])
let data = [
["created": NSDate(timeIntervalSince1970: 1422600000), "reps": 0],
["created": NSDate(timeIntervalSince1970: 1422600000), "reps": 1],
["created": NSDate(timeIntervalSince1970: 1422600000), "reps": 1],
["created": NSDate(timeIntervalSince1970: 1422700000), "reps": 0],
["created": NSDate(timeIntervalSince1970: 1422700000), "reps": 0],
]
func buildIndex(records: [[String: NSObject]]) -> [Session] {
var result = [Session]()
var dates = [NSDate]()
// Seperate out all the dates
for rec in records {
let date = rec["created"] as NSDate
if !contains(dates, date) {
dates.append(date)
}
}
// Find all the reps for each date
for date in dates {
var repsForDate = [Int]()
for rec in records {
let created = rec["created"] as NSDate
if created == date {
let reps = rec["reps"] as Int
repsForDate.append(reps)
}
}
result.append((date, repsForDate))
}
// Return results
return result
}
let days = buildIndex(data)
// Looping over all the days returns the day and the reps
for (day, reps) in days {
println(day)
for rep in reps {
println(rep)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment