-
Notifications
You must be signed in to change notification settings - Fork 5
/
Graph+FilterAndMap.swift
90 lines (75 loc) · 2.19 KB
/
Graph+FilterAndMap.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
90
public extension Graph
{
// MARK: - Value Mapper
func map<MappedValue>(_ transform: (NodeValue) throws -> MappedValue) rethrows -> Graph<NodeID, MappedValue, EdgeWeight>
{
let idsWithMappedValues = try nodes.map { ($0.id, try transform($0.value)) }
return .init(valuesByID: .init(uniqueKeysWithValues: idsWithMappedValues),
edges: edges)
}
// MARK: - Edge Filters
func filteredEdges(_ isIncluded: EdgeIDs) -> Self
{
var result = self
result.filterEdges(isIncluded)
return result
}
mutating func filterEdges(_ isIncluded: EdgeIDs)
{
filterEdges { isIncluded.contains($0.id) }
}
func filteredEdges(_ isIncluded: (Edge) throws -> Bool) rethrows -> Self
{
var result = self
try result.filterEdges(isIncluded)
return result
}
mutating func filterEdges(_ isIncluded: (Edge) throws -> Bool) rethrows
{
try edges.forEach
{
if try !isIncluded($0)
{
removeEdge(with: $0.id)
}
}
}
// MARK: - Value Filters
func filtered(_ isIncluded: (NodeValue) throws -> Bool) rethrows -> Self
{
var result = self
try result.filter(isIncluded)
return result
}
mutating func filter(_ isIncluded: (NodeValue) throws -> Bool) rethrows
{
try filterNodes { try isIncluded($0.value) }
}
// MARK: - Node Filters
func filteredNodes(_ isIncluded: NodeIDs) -> Self
{
var result = self
result.filterNodes(isIncluded)
return result
}
mutating func filterNodes(_ isIncluded: NodeIDs)
{
filterNodes { isIncluded.contains($0.id) }
}
func filteredNodes(_ isIncluded: (Node) throws -> Bool) rethrows -> Self
{
var result = self
try result.filterNodes(isIncluded)
return result
}
mutating func filterNodes(_ isIncluded: (Node) throws -> Bool) rethrows
{
try nodes.forEach
{
if try !isIncluded($0)
{
removeNode(with: $0.id)
}
}
}
}