SPB Git

Repository Public

Format.swift 11.8 KB 269 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Core/Util/Format.swift10// Description      : formats d'affichage (français du Québec) et petites aides11//                    de texte.12// Module           : LouKa13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192enum Fmt {93    static let locale = Locale(identifier: "fr_CA")9495    private static let intStyle = IntegerFormatStyle<Int>.number.locale(locale).grouping(.automatic)9697    /// 1 23498    static func int(_ n: Int?) -> String {99        guard let n else { return "—" }100        return n.formatted(intStyle)101    }102103    static func int(_ d: Double?) -> String { int(d.map { Int($0.rounded()) }) }104105    /// 1 234 $106    static func money(_ d: Double?) -> String {107        guard let d else { return "—" }108        return "\(int(d)) $"109    }110111    /// Pastille de carte : 950 → « 950 », 1 695 → « 1,7 k »112    static func shortPrice(_ d: Double?) -> String {113        guard let d, Listing.priceIsPlausible(d) else { return "•" }114        if d < 1000 { return String(Int(d.rounded())) }115        let k = (d / 100).rounded() / 10116        let s = k == k.rounded() ? String(Int(k)) : String(format: "%.1f", k).replacingOccurrences(of: ".", with: ",")117        return "\(s) k"118    }119120    /// -0,167 → « −17 % »121    static func pct(_ x: Double?, signed: Bool = true) -> String {122        guard let x else { return "—" }123        let v = Int((x * 100).rounded())124        let sign = (!signed || v == 0) ? "" : (v > 0 ? "+" : "−")125        return "\(sign)\(abs(v)) %"126    }127128    /// 250 → « 250 m », 1240 → « 1,2 km »129    static func distance(_ m: Double?) -> String {130        guard let m else { return "—" }131        if m < 1000 { return "\(Int((m / 10).rounded()) * 10) m" }132        return String(format: "%.1f km", m / 1000).replacingOccurrences(of: ".", with: ",")133    }134135    /// Horodatage Unix → « il y a 3 h »136    static func ago(_ ts: Double?) -> String {137        guard let ts, ts > 0 else { return "—" }138        let s = max(0, Date().timeIntervalSince1970 - ts)139        if s < 90 { return "à l'instant" }140        if s < 3600 { return "il y a \(Int((s / 60).rounded())) min" }141        if s < 86400 { return "il y a \(Int((s / 3600).rounded())) h" }142        let d = Int((s / 86400).rounded())143        if d < 31 { return "il y a \(d) j" }144        if d < 365 { return "il y a \(Int((Double(d) / 30).rounded())) mois" }145        let y = Int((Double(d) / 365).rounded())146        return "il y a \(y) an\(y > 1 ? "s" : "")"147    }148149    static func date(_ ts: Double?) -> String {150        guard let ts, ts > 0 else { return "—" }151        return Date(timeIntervalSince1970: ts).formatted(.dateTime.day().month(.wide).year().locale(locale))152    }153154    /// « now » → « Maintenant », « 2026-12-01 » → « 1ᵉʳ décembre »155    static func availability(_ iso: String?, withYear: Bool = false) -> String? {156        guard let iso, !iso.isEmpty else { return nil }157        if iso == "now" { return "Maintenant" }158        let parts = iso.prefix(10).split(separator: "-").compactMap { Int($0) }159        guard parts.count == 3 else { return nil }160        var c = DateComponents(); c.year = parts[0]; c.month = parts[1]; c.day = parts[2]161        guard let d = Calendar(identifier: .gregorian).date(from: c) else { return nil }162        if d < Date() { return "Maintenant" }163        let style: Date.FormatStyle = withYear164            ? .dateTime.day().month(.wide).year().locale(locale)165            : .dateTime.day().month(.wide).locale(locale)166        let s = d.formatted(style)167        return s.hasPrefix("1 ") ? "1ᵉʳ " + s.dropFirst(2) : s168    }169170    static func plural(_ n: Int, _ one: String, _ many: String) -> String {171        "\(int(n)) \(n > 1 ? many : one)"172    }173174    /// Nettoie les libellés de ville mal formés publiés par certaines sources.175    static func cleanCity(_ c: String?) -> String {176        (c ?? "").replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "")177            .trimmingCharacters(in: .whitespacesAndNewlines)178    }179180    /// Slug identique à celui du serveur (seo.slugify).181    static func slug(_ text: String) -> String {182        var t = text.replacingOccurrences(of: "½", with: "-1-2").replacingOccurrences(of: "+", with: "-plus")183            .replacingOccurrences(of: "œ", with: "oe").replacingOccurrences(of: "Œ", with: "Oe")184        t = t.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "en_US")).lowercased()185        var out = ""186        var dash = false187        for ch in t.unicodeScalars {188            if (ch.value >= 97 && ch.value <= 122) || (ch.value >= 48 && ch.value <= 57) {189                out.unicodeScalars.append(ch); dash = false190            } else if !dash, !out.isEmpty {191                out.append("-"); dash = true192            }193        }194        return out.hasSuffix("-") ? String(out.dropLast()) : out195    }196197    /// Nom lisible de repli pour un identifiant de source (« groupe_xyz » → « Groupe Xyz »).198    static func prettySource(_ id: String) -> String {199        id.replacingOccurrences(of: "_", with: " ").capitalized(with: locale)200    }201202    /// Jours d'ici une date ISO (négatif si passée).203    static func daysUntil(iso: String) -> Int? {204        let parts = iso.prefix(10).split(separator: "-").compactMap { Int($0) }205        guard parts.count == 3 else { return nil }206        var c = DateComponents(); c.year = parts[0]; c.month = parts[1]; c.day = parts[2]207        guard let d = Calendar(identifier: .gregorian).date(from: c) else { return nil }208        return Calendar.current.dateComponents([.day], from: Calendar.current.startOfDay(for: Date()), to: d).day209    }210211    /// « 2026-11-23 » → « 23 novembre » ; `year` ajoute l'année.212    static func isoDay(_ iso: String?, year: Bool = false) -> String {213        guard let iso else { return "—" }214        let parts = iso.prefix(10).split(separator: "-").compactMap { Int($0) }215        guard parts.count == 3 else { return iso }216        var c = DateComponents(); c.year = parts[0]; c.month = parts[1]; c.day = parts[2]217        guard let d = Calendar(identifier: .gregorian).date(from: c) else { return iso }218        let style: Date.FormatStyle = year ? .dateTime.day().month(.wide).year().locale(locale) : .dateTime.day().month(.wide).locale(locale)219        let s = d.formatted(style)220        return s.hasPrefix("1 ") ? "1ᵉʳ " + s.dropFirst(2) : s221    }222223    /// « 2026-10-01 » → « octobre 2026 »224    static func isoMonth(_ iso: String?) -> String {225        guard let iso else { return "—" }226        let parts = iso.prefix(10).split(separator: "-").compactMap { Int($0) }227        guard parts.count >= 2 else { return iso }228        var c = DateComponents(); c.year = parts[0]; c.month = parts[1]; c.day = 1229        guard let d = Calendar(identifier: .gregorian).date(from: c) else { return iso }230        return d.formatted(.dateTime.month(.wide).year().locale(locale))231    }232233    static func isoDate(_ iso: String?) -> Date? {234        guard let iso else { return nil }235        let parts = iso.prefix(10).split(separator: "-").compactMap { Int($0) }236        guard parts.count == 3 else { return nil }237        var c = DateComponents(); c.year = parts[0]; c.month = parts[1]; c.day = parts[2]238        return Calendar(identifier: .gregorian).date(from: c)239    }240241    /// Pour cent déjà exprimé en points : −21,18 → « −21,2 % » ; `digits` décimales.242    static func points(_ x: Double?, digits: Int = 1, signed: Bool = true) -> String {243        guard let x else { return "—" }244        let v = abs(x).formatted(.number.precision(.fractionLength(0...digits)).locale(locale))245        let sign = !signed || abs(x) < 0.05 ? "" : (x > 0 ? "+" : "−")246        return "\(sign)\(v) %"247    }248249    /// 2,76 $ / pi²250    static func perSqft(_ x: Double?) -> String {251        guard let x else { return "—" }252        return x.formatted(.number.precision(.fractionLength(2)).locale(locale)) + " $/pi²"253    }254255    /// Nombre à décimales françaises : 101,4256    static func dec(_ x: Double?, _ digits: Int = 1) -> String {257        guard let x else { return "—" }258        return x.formatted(.number.precision(.fractionLength(digits)).locale(locale))259    }260261    /// Date ISO à +n jours (filtre « disponible d'ici… »).262    static func isoInDays(_ n: Int) -> String {263        let d = Calendar.current.date(byAdding: .day, value: n, to: Date()) ?? Date()264        let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian)265        f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd"266        return f.string(from: d)267    }268}269
Files main
Menu

Theme