Skip to content

Instantly share code, notes, and snippets.

@tobins
Created February 13, 2019 19:32
Show Gist options
  • Save tobins/1e30c9f739cda75f5fa4b6c120ec5fa1 to your computer and use it in GitHub Desktop.
Save tobins/1e30c9f739cda75f5fa4b6c120ec5fa1 to your computer and use it in GitHub Desktop.
Diff two arrays in swift
import UIKit
var left:[Int] = [1,1,1,1,1]
var right:[Int] = [1,2,2,2,2,2,2,1]
enum Difference {
case insert(Int, Any)
case delete(Int, Any)
}
extension Array where Element:Equatable {
func diff(_ to:Array<Element>) -> Array<Difference> {
var first:[Difference] = []
var second:[Difference] = []
var temp:[Element] = to
self.enumerated().forEach { (index, value) in
if let found = temp.firstIndex(of: value) {
temp.remove(at: found)
return
}
first.append(.delete(index, value))
}
var new:[Element] = self
first.reversed().forEach { (action) in
switch action {
case .delete(let index, _):
new.remove(at: index)
break
default:
break
}
}
to.enumerated().forEach { (index, value) in
if new.count == index {
new.append(value)
first.append(.insert(index, value))
return
}
if new[index] == value {
return
}
new.insert(value, at: index)
first.append(.insert(index, value))
}
temp = to
new.enumerated().forEach { (index, value) in
if let found = temp.firstIndex(of: value) {
temp.remove(at: found)
return
}
second.append(.delete(index, value))
}
second.reversed().forEach { (action) in
switch action {
case .delete(let index, _):
new.remove(at: index)
break
default:
break
}
}
return first + second
}
}
let actions = left.diff(right).map { (action) -> String in
switch action {
case .insert(let index, let value):
return "+\(index):\(value)"
case .delete(let index, let value):
return "-\(index):\(value)"
}
}
print(actions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment