diff --git a/Sources/Extensions/Array/Array+Extensions.swift b/Sources/Extensions/Array/Array+Extensions.swift index 1d3d58e9..c4818fa9 100644 --- a/Sources/Extensions/Array/Array+Extensions.swift +++ b/Sources/Extensions/Array/Array+Extensions.swift @@ -20,7 +20,49 @@ // THE SOFTWARE. // -public extension Array { +public extension Array where Element: Equatable { + + /// Union array with another arrays, without element duplication + func union(values: [Array.Element]...) -> Array { + var result = self + + for array in values { + for value in array { + if !result.contains(value) { + result.append(value) + } + } + } + + return result + } + + /// Find common elements among arrays + func intersection(values: [Array.Element]...) -> Array { + var result = self + var intersection = Array() + + for (index, value) in values.enumerated() { + if index > 0 { + result = intersection + intersection = Array() + } + + value.forEach { item in + if result.contains(item) && !intersection.contains(item) { + intersection.append(item) + } + } + } + + return intersection + } + + /// Find unique elements in array compared to other arrays + func subtract(values: [Array.Element]...) -> Array { + let allValues = values.flatMap { $0 } + return filter { !allValues.contains($0) } + } // Subscript for safe access to element by index subscript(safe index: Index) -> Element? {