Last active
August 9, 2018 10:13
-
-
Save albertbori/0b26c8190ab0469e49d7e4714f18ffe9 to your computer and use it in GitHub Desktop.
An extension for Swift Array that returns the difference between two arrays
This file contains 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
//: Playground - noun: a place where people can play | |
extension Array where Element: Comparable { | |
/** | |
Compares array with passed array and returns the differences. Warning: Must be a set of data (no duplicate values) | |
- Parameter with: The new array to compare to the existing array | |
- Returns: A tuple with an array of added items and an array of removed items. | |
*/ | |
func diff(with array: Array) -> (added: Array, removed: Array) { | |
let originalArray = self.sorted() | |
let newArray = array.sorted() | |
var addedItems: [Element] = [] | |
var removedItems: [Element] = [] | |
var originalIndex = 0 | |
var newIndex = 0 | |
while originalIndex < originalArray.count && newIndex < newArray.count { | |
if originalArray[originalIndex] < newArray[newIndex] { | |
removedItems.append(originalArray[originalIndex]) | |
originalIndex += 1 | |
} else if originalArray[originalIndex] > newArray[newIndex] { | |
addedItems.append(newArray[newIndex]) | |
newIndex += 1 | |
} else { | |
newIndex += 1 | |
originalIndex += 1 | |
} | |
} | |
if newIndex < newArray.count { | |
addedItems.append(contentsOf: newArray[newIndex..<newArray.count]) | |
} | |
if originalIndex < originalArray.count { | |
removedItems.append(contentsOf: originalArray[originalIndex..<originalArray.count]) | |
} | |
return (added: addedItems, removed: removedItems) | |
} | |
} | |
let original = [7, 3, 4, 6] | |
let new = [2, 4, 9, 10, 7] | |
let result = original.diff(with: new) | |
print(result.added) //prints [2, 9, 10] | |
print(result.removed) //prints [3, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or just use set: