Cotton code
51 lines · 2.1 KB · SwiftRaw
import Foundation/// The few words the popover composes from the core's numbers.enum Words {    static func date(_ iso: String?) -> Date? {        guard let iso else { return nil }        return (try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(iso))            ?? (try? Date.ISO8601FormatStyle().parse(iso))    }    /// "just now", "2 min ago", "today 16:10", "yesterday 09:12", "12 Oct".    static func ago(_ date: Date, now: Date = Date()) -> String {        let seconds = now.timeIntervalSince(date)        if seconds < 60 { return "just now" }        if seconds < 3600 { return "\(Int(seconds / 60)) min ago" }        let calendar = Calendar.current        let clock = date.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits))        if calendar.isDate(date, inSameDayAs: now) { return "today \(clock)" }        if let yesterday = calendar.date(byAdding: .day, value: -1, to: now),           calendar.isDate(date, inSameDayAs: yesterday) {            return "yesterday \(clock)"        }        return date.formatted(.dateTime.day().month(.abbreviated))    }    static func count(_ n: Int, _ noun: (one: String, many: String)) -> String {        "\(n) \(n == 1 ? noun.one : noun.many)"    }    /// "+91 98765 43210" for an Indian number, the number as given otherwise.    static func phone(_ phone: String?) -> String? {        guard let phone, !phone.isEmpty else { return nil }        let digits = phone.filter(\.isNumber)        if phone.hasPrefix("+91"), digits.count == 12 {            let national = digits.dropFirst(2)            return "+91 \(national.prefix(5)) \(national.suffix(5))"        }        return phone    }    /// "every 15 min", "hourly", "continuous": the core's label, in the mock's case.    static func schedule(_ label: String) -> String {        label.lowercased()    }    /// "about 20 s left", "about 3 min left".    static func left(_ seconds: Double) -> String {        if seconds < 90 { return "about \(max(1, Int(seconds.rounded()))) s left" }        return "about \(Int((seconds / 60).rounded())) min left"    }}