// // Array+Extensions.swift // PadelClub // // Created by Razmig Sarkissian on 03/03/2024. // import Foundation extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: count, by: size).map { Array(self[$0 ..< Swift.min($0 + size, count)]) } } func anySatisfy(_ p: (Element) -> Bool) -> Bool { return first(where: { p($0) }) != nil //return !self.allSatisfy { !p($0) } } // Check if the number of elements in the sequence is even var isEven: Bool { return self.count % 2 == 0 } // Check if the number of elements in the sequence is odd var isOdd: Bool { return self.count % 2 != 0 } } extension Array where Element: Equatable { /// Remove first collection element that is equal to the given `object` or `element`: mutating func remove(elements: [Element]) { elements.forEach { if let index = firstIndex(of: $0) { remove(at: index) } } } } extension Array where Element: CustomStringConvertible { func customJoined(separator: String, lastSeparator: String) -> String { switch count { case 0: return "" case 1: return "\(self[0])" case 2: return "\(self[0]) \(lastSeparator) \(self[1])" default: let firstPart = dropLast().map { "\($0)" }.joined(separator: ", ") let lastPart = "\(lastSeparator) \(last!)" return "\(firstPart) \(lastPart)" } } } extension Dictionary where Key == Int, Value == [String] { mutating func setOrAppend(_ element: String?, at key: Int) { // Check if the element is nil; do nothing if it is guard let element = element else { return } // Check if the key exists in the dictionary if var array = self[key] { // If it exists, append the element to the array array.append(element) self[key] = array } else { // If it doesn't exist, create a new array with the element self[key] = [element] } } } extension Array where Element == String { func formatList(maxDisplay: Int = 2) -> [String] { // Check if the array has fewer or equal elements than the maximum display limit if self.count <= maxDisplay { // Join all elements with commas return self } else { // Join only the first `maxDisplay` elements and add "et plus" let displayedItems = self.prefix(maxDisplay) let remainingCount = self.count - maxDisplay return displayedItems.dropLast() + [displayedItems.last! + " et \(remainingCount) de plus"] } } }