Module: Tins::HashBFS
- Extended by:
- ThreadLocal
- Defined in:
- lib/tins/hash_bfs.rb
Instance Method Summary
collapse
instance_thread_local, thread_local
Instance Method Details
#bfs(include_nodes: false, &block) ⇒ Object
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
|
# File 'lib/tins/hash_bfs.rb', line 9
def bfs(include_nodes: false, &block)
block or raise ArgumentError, 'require &block argument'
self.seen = {}
queue = []
queue.push([ nil, self ])
while (index, object = queue.shift)
case
when seen[object.__id__]
next
when Hash === object
seen[object.__id__] = true
object.each do |k, v|
queue.push([ k, convert_to_hash_or_ary(v) ])
end
include_nodes or next
when Array === object
seen[object.__id__] = true
object.each_with_index do |v, i|
queue.push([ i, convert_to_hash_or_ary(v) ])
end
include_nodes or next
end
block.(index, object)
end
self
ensure
self.seen = nil
end
|
#convert_to_hash_or_ary(v) ⇒ Object
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/tins/hash_bfs.rb', line 38
def convert_to_hash_or_ary(v)
case
when v.respond_to?(:to_hash)
v = v.to_hash
when v.respond_to?(:to_ary)
v = v.to_ary
else
v
end
end
|