feat: Implement abbreviated status counts

This commit is contained in:
Marcus Kida 2022-12-28 11:52:44 +01:00
parent b65bf9155b
commit 6c260f942f
No known key found for this signature in database
GPG Key ID: 19FF64E08013CA40
3 changed files with 86 additions and 1 deletions

View File

@ -0,0 +1,31 @@
//
// Int.swift
//
//
// Created by Marcus Kida on 28.12.22.
//
import Foundation
public extension Int {
func asAbbreviatedCountString() -> String {
switch self {
case ..<1_000:
return String(format: "%d", locale: Locale.current, self)
case 1_000 ..< 999_999:
return String(format: "%.1fK", locale: Locale.current, Double(self) / 1_000)
.sanitizedAbbreviatedCountString(for: "K")
default:
return String(format: "%.1fM", locale: Locale.current, Double(self) / 1_000_000)
.sanitizedAbbreviatedCountString(for: "M")
}
}
}
fileprivate extension String {
func sanitizedAbbreviatedCountString(for value: String) -> String {
[".0", ",0", "٫٠"].reduce(self) { res, acc in
return res.replacingOccurrences(of: "\(acc)\(value)", with: value)
}
}
}

View File

@ -9,6 +9,7 @@ import os.log
import UIKit
import MastodonAsset
import MastodonLocalization
import MastodonExtension
public protocol ActionToolbarContainerDelegate: AnyObject {
func actionToolbarContainer(_ actionToolbarContainer: ActionToolbarContainer, buttonDidPressed button: UIButton, action: ActionToolbarContainer.Action)
@ -283,7 +284,7 @@ extension ActionToolbarContainer {
extension ActionToolbarContainer {
private static func title(from number: Int?) -> String {
guard let number = number, number > 0 else { return "" }
return String(number)
return number.asAbbreviatedCountString()
}
}

View File

@ -0,0 +1,53 @@
//
// IntTests.swift
//
//
// Created by Marcus Kida on 28.12.22.
//
import XCTest
@testable import MastodonSDK
class IntFriendlyCountTests: XCTestCase {
func testFriendlyCount_for_1000() {
let input = 1_000
let expectedOutput = "1K"
XCTAssertEqual(expectedOutput, input.asAbbreviatedCountString())
}
func testFriendlyCount_for_1200() {
let input = 1_200
let expectedOutput = "1.2K"
XCTAssertEqual(expectedOutput, input.asAbbreviatedCountString())
}
func testFriendlyCount_for_50000() {
let input = 50_000
let expectedOutput = "50K"
XCTAssertEqual(expectedOutput, input.asAbbreviatedCountString())
}
func testFriendlyCount_for_70666() {
let input = 70_666
let expectedOutput = "70.7K"
XCTAssertEqual(expectedOutput, input.asAbbreviatedCountString())
}
func testFriendlyCount_for_1M() {
let input = 1_000_000
let expectedOutput = "1M"
XCTAssertEqual(expectedOutput, input.asAbbreviatedCountString())
}
func testFriendlyCount_for_1dot5M() {
let input = 1_499_000
let expectedOutput = "1.5M"
XCTAssertEqual(expectedOutput, input.asAbbreviatedCountString())
}
}