Module: Tins::HashBFS
- Extended by:
- ThreadLocal
- Defined in:
- lib/tins/hash_bfs.rb
Overview
HashBFS module for breadth-first traversal of hash structures
Provides methods to traverse hash structures in a breadth-first manner, visiting all keys and values while maintaining the order of traversal.
Instance Method Summary collapse
-
#bfs(visit_internal: false) {|index, value| ... } ⇒ self
The bfs method performs a breadth-first search on the object’s structure, visiting all elements and yielding their indices and values to the block.
-
#convert_to_hash_or_ary(object) ⇒ Hash, ...
Converts the given object into a hash or array if possible.
Methods included from ThreadLocal
instance_thread_local, thread_local
Instance Method Details
#bfs(visit_internal: false) {|index, value| ... } ⇒ self
The bfs method performs a breadth-first search on the object’s structure, visiting all elements and yielding their indices and values to the block.
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 |
# File 'lib/tins/hash_bfs.rb', line 24 def bfs(visit_internal: 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 visit_internal 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 visit_internal or next end block.(index, object) end self ensure self.seen = nil end |
#convert_to_hash_or_ary(object) ⇒ Hash, ...
Converts the given object into a hash or array if possible
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/tins/hash_bfs.rb', line 58 def convert_to_hash_or_ary(object) case when object.respond_to?(:to_hash) object.to_hash when object.respond_to?(:to_ary) object.to_ary else object end end |