From 71721c5bb1e7fecdb149ca5562157a72cb386673 Mon Sep 17 00:00:00 2001 From: Ivan Smolin Date: Thu, 19 Oct 2017 18:07:05 +0300 Subject: [PATCH] bring back array extensions --- .../Extensions/Array/Array+Extensions.swift | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) 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? {