-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathCursorDeepFirstSearchTests.swift
More file actions
91 lines (80 loc) · 2.4 KB
/
CursorDeepFirstSearchTests.swift
File metadata and controls
91 lines (80 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import Foundation
import XCTest
@testable import ASTParser
class CursorDeepFirstSearchTests: XCTestCase {
class TN {
var parent: TN?
var value: Int
var children: [TN] = []
init(_ value: Int, _ children: [TN] = []) {
self.value = value
self.children = children
children.forEach { $0.parent = self }
}
}
class ACursor: Cursor {
var currentNode: TN?
init(currentNode: TN?) {
self.currentNode = currentNode
}
func goToFirstChild() -> Bool {
if let first = currentNode?.children.first {
currentNode = first
return true
}
return false
}
func goToNextSibling() -> Bool {
if let parent = currentNode?.parent,
let index = parent.children.firstIndex(where: { $0 === currentNode }),
index < parent.children.count - 1 {
currentNode = parent.children[index + 1]
return true
}
return false
}
func goToParent() -> Bool {
if let parent = currentNode?.parent {
currentNode = parent
return true
}
return false
}
}
func test_deep_first_search() {
let root = TN(0, [
TN(1, [
TN(2),
TN(3)
]),
TN(4, [
TN(5, [TN(6, [TN(7)])]),
TN(8)
])
])
let cursor = ACursor(currentNode: root)
var result = [Int]()
for node in CursorDeepFirstSearchSequence(cursor: cursor, skipChildren: { _ in true }) {
result.append(node.value)
}
XCTAssertEqual(result, result.sorted())
}
func test_deep_first_search_skip_children() {
let root = TN(0, [
TN(1, [
TN(2),
TN(3)
]),
TN(4, [
TN(5, [TN(6, [TN(7)])]),
TN(8)
])
])
let cursor = ACursor(currentNode: root)
var result = [Int]()
for node in CursorDeepFirstSearchSequence(cursor: cursor, skipChildren: { $0.value == 5 }) {
result.append(node.value)
}
XCTAssertEqual(result, [0, 1, 2, 3, 4, 5, 8])
}
}