-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathData.swift
89 lines (76 loc) · 1.87 KB
/
Data.swift
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
//
// Data.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 31/08/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
internal extension Array {
func toQueue() -> Queue<Element> {
return Queue<Element>(data: self)
}
}
open class TreeNode<T> {
open var value: T
open var parent: TreeNode?
open var children = [TreeNode<T>]()
public init(value v: T) {
value = v
}
func add(_ child: TreeNode<T>) -> TreeNode<T> {
children.append(child)
child.parent = self
return child
}
func add(_ child: T) -> TreeNode<T> {
let c = TreeNode<T>(value: child)
c.parent = self
children.append(c)
return c
}
var isLeaf: Bool {
return children.count == 0
}
var isRoot: Bool {
return parent == nil
}
var depth: Int {
if let p = parent {
return p.depth + 1
}
return 0
}
open func lookUp<Type>(_ type: Type.Type) -> Type? {
if let v = value as? Type {
return v
}
if let p = parent {
return p.lookUp(type)
}
return nil
}
}
extension TreeNode: CustomStringConvertible {
public var description: String {
let prefix = String(repeating: "-", count: depth)
var lines = ["\(prefix) \(value)"]
if !children.isEmpty {
lines += children.map { $0.description }
}
return lines.joined(separator: "\n")
}
}
public struct Progress {
public var total: Int = 0
public var done: Int = 0
public init(_ d: Int = 0, outof t: Int = 0) {
total = t
done = d
}
}
extension Progress: Equatable {
public static func ==(lhs: Progress, rhs: Progress) -> Bool {
return lhs.total == rhs.total && lhs.done == rhs.done
}
}