Created
August 27, 2021 12:29
-
-
Save MihailPreis/55ae7627193870caf59a2a5d9191779c to your computer and use it in GitHub Desktop.
Swift extension of Array for getting difference from two arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array where Element: Hashable { | |
/// Result entity for `diff(with:)` | |
typealias DiffResult = (old: [Element], changed: [Element], new: [Element]) | |
/** | |
Return difference between two arrays. | |
- Parameter newArray: New array. | |
- Returns: DiffResult entity with: | |
- old items from current array, | |
- changed intersection items from new array | |
- new items from new array. | |
*/ | |
func diff(with newArray: [Element]) -> DiffResult { | |
let itemsSet = Set(self) | |
let newItemsSet = Set(newArray) | |
return ( | |
Array(itemsSet.subtracting(newItemsSet)), | |
Array(newItemsSet.intersection(itemsSet)), | |
Array(newItemsSet.subtracting(itemsSet)) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment