Skip to content

Instantly share code, notes, and snippets.

@tatimagdalena
Last active October 20, 2023 08:30
Show Gist options
  • Save tatimagdalena/eb6f551c4dd36b0b483802ad9a4d2638 to your computer and use it in GitHub Desktop.
Save tatimagdalena/eb6f551c4dd36b0b483802ad9a4d2638 to your computer and use it in GitHub Desktop.
private extension Array {
func chunked(into size: Int) -> [[Element]] {
stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
static func += (lhs: inout Self, rhs: Self.Element) {
lhs.append(rhs)
}
subscript(safeIndex indice: Int) -> Element? {
indices.contains(index(indice, offsetBy: 0)) ? self[indice] : nil
}
mutating func insertFirst(_ item: Element, limit: Int) {
insert(item, at: 0)
if count > limit { _ = removeLast() }
}
func doesNotContain(where predicate: (Element) throws -> Bool) rethrows -> Bool {
try !contains(where: predicate)
}
func uniques<T: Hashable>(by keyPath: KeyPath<Element, T>) -> [Element] {
var seen = Set<T>()
return filter {
seen.insert($0[keyPath: keyPath]).inserted
}
}
func appending(_ newElement: Element) -> [Element] {
var mutableSelf = self
mutableSelf.append(newElement)
return mutableSelf
}
func mapAsStringArray<T> (callback: (T) -> String?) -> [String] {
var map: [String] = []
for element in self {
guard let val = element as? T else {
continue
}
guard let value = callback(val) else {
map.append("")
continue
}
map.append(value)
}
return map
}
}
public extension Array where Array.Element: Hashable {
/// Creates a union of two arrays.
///
/// When an element is present in both arrays, the one in
/// the method's parameter array replaces the one in self.
///
/// - parameter array: The array to be merged into self.
///
/// - returns: The union of both arrays.
///
func merged(with array: [Element]) -> [Element] {
Array(Set(array + self))
}
}
public extension Sequence where Iterator.Element: Hashable {
func unique() -> [Iterator.Element] {
var seen: [Iterator.Element: Bool] = [:]
return filter { seen.updateValue(true, forKey: $0) == nil }
}
func group<U: Hashable>(by key: (Iterator.Element) -> U) -> [U:[Iterator.Element]] {
Dictionary.init(grouping: self, by: key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment