Skip to content

Instantly share code, notes, and snippets.

@algal
Last active July 30, 2018 09:15
Show Gist options
  • Save algal/5686af4dec652c4ce773 to your computer and use it in GitHub Desktop.
Save algal/5686af4dec652c4ce773 to your computer and use it in GitHub Desktop.
diff calculator
// swift 1.2
/**
:param: old array of items
:param: new array of items
:return: a tuple where with the following components:
- `newIndexesAdded` indexes in new, for elements that did not exist in old
- `oldIndexesDeleted` indexes in old, for elements not in new
- `indexesOfMovedItems` array of (oldIndex,newIndex) pairs, indicating the change in index of an item that exists in old and in new and has a different index in old than in new
*/
func diffs<T:Hashable>(old: [T], new: [T]) ->
(newIndexesAdded:[Int],oldIndexesDeleted:[Int],indexesOfMovedItems:[(Int,Int)])
{
let newMinusOld = Array(Set(new).subtract(Set(old)))
let oldMinusNew = Array(Set(old).subtract(Set(new)))
let oldIntersectNew = Array(Set(new).intersect(Set(old)))
let newIndexesAdded = newMinusOld.map { find(new,$0)! }
let oldIndexesDeleted = oldMinusNew.map { find(old,$0)! }
let moved = oldIntersectNew
let moves:[(Int,Int)] = moved.map({ (find(old,$0)!,find(new,$0)!)}).filter({$0 != $1})
return (
newIndexesAdded:newIndexesAdded,
oldIndexesDeleted:oldIndexesDeleted,
indexesOfMovedItems:moves
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment