Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/jumoku/ext/ext.rb

Overview

FIXME: nest this into Jumoku’s namespace and inherit from stdlib classes

Instance Method Summary collapse

Instance Method Details

#create_branches_list(branch_type) ⇒ Object

Create a list of branches object based on an expandable array of nodes.

TODO: refacto, it’s painful having to pass the branch_type

Parameters:

  • branch_type (DirectedBranch, UndirectedBranch)


52
53
54
55
56
# File 'lib/jumoku/ext/ext.rb', line 52

def create_branches_list(branch_type)
  branches = []
  self.expand_branches!.each_by(2) { |pair| branches << branch_type.new(pair[0], pair[1]) }
  branches
end

#create_nodes_pairs_listArray(nodes)

Creates nodes pairs from a flat array specifying unique nodes.

b = [1, 2, 3, "foo", :bar, Array.new]
b.create_nodes_pairs
=> [1, 2, 2, 3, 3, "foo", "foo", :bar, :bar, []]

Returns:



42
43
44
# File 'lib/jumoku/ext/ext.rb', line 42

def create_nodes_pairs_list
  self.create_pairs.flatten(1)
end

#create_pairsObject



31
32
33
# File 'lib/jumoku/ext/ext.rb', line 31

def create_pairs
  self.map_with_index { |e,i| ((pairs ||= []) << e).concat(self.values_at(i+1)) }[0..-2]
end

#each_nodes_pairObject

Takes a flat array of nodes pairs and yield them to the block.



5
6
7
8
# File 'lib/jumoku/ext/ext.rb', line 5

def each_nodes_pair
  raise if self.size % 2 != 0
  each_by(2) { |pair| yield pair }
end

#expand_branches!*nodes

Fetches the positions of Branch items in an array, and expands them in place as nodes pairs.

expand_branches!(1,2, Branch.new(2, 3), 3,4, 4,5)
# => 1,2, 2,3, 3,4, 4,5

Parameters:

  • *a (*nodes, *Branch)

    a flat list of nodes pairs and branches

Returns:

  • (*nodes)

    a flat list of nodes pairs



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/jumoku/ext/ext.rb', line 18

def expand_branches!
  branches_positions = self.dup.map_send(:"is_a?", Jumoku::Branch).map_with_index { |e,i| i if e == true }.compact
  # obviously positions will gain an offset of 1 for each expanded branch,
  # so let's correct this right away
  branches_positions = branches_positions.map_with_index { |e,i| e += i }
  branches_positions.each do |pos|
    branch = self.delete_at pos
    self.insert pos,   branch.source
    self.insert pos+1, branch.target
  end
  return self
end