Add descendantNodeRepresentingObject to Node.swift.

This commit is contained in:
Brent Simmons 2018-01-27 12:03:17 -08:00
parent 5888e1b7d0
commit 7ba2fe72dd

View File

@ -115,16 +115,12 @@ public final class Node: Hashable {
public func childNodeRepresentingObject(_ obj: AnyObject) -> Node? {
guard let childNodes = childNodes else {
return nil
return findNodeRepresentingObject(obj, recursively: false)
}
for oneNode in childNodes {
if oneNode.representedObject === obj {
return oneNode
}
}
return nil
public func descendantNodeRepresentingObject(_ obj: AnyObject) -> Node? {
return findNodeRepresentingObject(obj, recursively: true)
}
public func hasAncestor(in nodes: [Node]) -> Bool {
@ -198,3 +194,23 @@ public extension Array where Element == Node {
return self.map{ $0.representedObject }
}
}
private extension Node {
func findNodeRepresentingObject(_ obj: AnyObject, recursively: Bool = false) -> Node? {
guard let childNodes = childNodes else {
return nil
}
for childNode in childNodes {
if childNode.representedObject === obj {
return childNode
}
if recursively, let foundNode = childNode.descendantNodeRepresentingObject(obj) {
return foundNode
}
}
return nil
}
}