Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Created October 15, 2017 04:48
Show Gist options
  • Save jakebromberg/12ecb4f27506d53403fe5f38a5127c0b to your computer and use it in GitHub Desktop.
Save jakebromberg/12ecb4f27506d53403fe5f38a5127c0b to your computer and use it in GitHub Desktop.
extension Collection where Iterator.Element: Equatable {
/// Computes the indices of different elements between two collections. This is useful for updating table views
/// with row deletions and insertion
/// - Parameter other: the collection to compute the index difference
/// - Returns: a tuple with indices to delete and insert on `self` to create a collection equivalent to `other`
/// - Discussion: This algorithm does not work for collections with duplicate elements.
public func indexDifference(with other: Self) -> (deleted: [Index], inserted: [Index]) {
var (deleted, inserted): ([Index], [Index]) = ([], [])
for (offset, element) in self.enumerated() where !other.contains(element) {
let i = index(startIndex, offsetBy: numericCast(offset))
deleted.append(i)
}
for (offset, element) in other.enumerated() where !self.contains(element) {
let i = index(startIndex, offsetBy: numericCast(offset))
inserted.append(i)
}
return (deleted, inserted)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment