From d3a071804e22214fd5395a337fa281aa7ef991db Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Thu, 4 Jun 2026 10:04:28 -0700 Subject: [PATCH] Add common comparison functions. --- Modules/RSCore/Sources/RSCore/Comparing.swift | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Modules/RSCore/Sources/RSCore/Comparing.swift diff --git a/Modules/RSCore/Sources/RSCore/Comparing.swift b/Modules/RSCore/Sources/RSCore/Comparing.swift new file mode 100644 index 000000000..fb903258f --- /dev/null +++ b/Modules/RSCore/Sources/RSCore/Comparing.swift @@ -0,0 +1,61 @@ +// +// Comparing.swift +// RSCore +// +// Created by Brent Simmons on 6/3/26. +// + +import Foundation + +// Helpers for `Array.sort` closures. + +/// Compare using `localizedCaseInsensitiveCompare`. +public func compareStrings(_ lhs: String, _ rhs: String, ascending: Bool) -> Bool { + let result = lhs.localizedCaseInsensitiveCompare(rhs) + return ascending ? result == .orderedAscending : result == .orderedDescending +} + +public func compareValues(_ lhs: T, _ rhs: T, ascending: Bool) -> Bool { + ascending ? lhs < rhs : lhs > rhs +} + +/// Compare optional `Comparable` values. Nil sorts before non-nil when ascending. +public func compareOptionals(_ lhs: T?, _ rhs: T?, ascending: Bool) -> Bool { + switch (lhs, rhs) { + case (nil, nil): + return false + case (nil, _): + return ascending + case (_, nil): + return !ascending + case let (l?, r?): + return ascending ? l < r : l > r + } +} + +// Direction-free comparisons returning `ComparisonResult`. Use when chaining a +// tiebreaker — apply the ascending flag once at the end. + +public func compareValues(_ lhs: T, _ rhs: T) -> ComparisonResult { + if lhs < rhs { + return .orderedAscending + } + if lhs > rhs { + return .orderedDescending + } + return .orderedSame +} + +/// Compare optional `Comparable` values. Nil sorts before non-nil. +public func compareOptionals(_ lhs: T?, _ rhs: T?) -> ComparisonResult { + switch (lhs, rhs) { + case (nil, nil): + return .orderedSame + case (nil, _): + return .orderedAscending + case (_, nil): + return .orderedDescending + case let (l?, r?): + return compareValues(l, r) + } +}