Method: Alml::Engine#script_map

Defined in:
lib/alml_engine.rb

#script_map(objects_to_map_array, &block) ⇒ Object

Helps to order the scripts, sending in a block to evaluate equality Returns an array, indexed by script_index, with all the objects in them that should be mapped, according to the layout (including :auto script keyword)



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
# File 'lib/alml_engine.rb', line 26

def script_map(objects_to_map_array, &block)
  objs = objects_to_map_array.dup
  ss = scripts
  script_map_array = Array.new(ss.length + 1)
  auto_fill_index = -1
  last_auto_index = -1 # Filled with anything remaining
  
    
  ss.each_with_index do |script_param, script_index|
    if script_param == ':auto'
      script_map_array[script_index] = Array.new
      last_auto_index = auto_fill_index = script_index
    elsif auto_fill_index != -1
      while auto_fill_index != -1 && obj = objs.shift
        if block.call(obj, script_param) # Next item matches
          script_map_array[script_index] = [obj]
          auto_fill_index = -1
        else
          script_map_array[auto_fill_index] << obj
        end
      end
      # if we've come out of here because objs.shift is empty and there was no match, then we shouldn't come back into this loop
      if auto_fill_index != -1 
        script_map_array[script_index] = []
        auto_fill_index = -1
      end
    else
      # Essentially, delete_first_if (&block)
      found_at = nil
      objs.each_with_index { |obj, i| found_at = i if block.call(obj, script_param) }
      script_map_array[script_index] = found_at.nil? ? [] : [objs.delete_at(found_at)]
    end
  end
  
  # Remaining, fill in auto; otherwise, just put it all the way at the end
  if last_auto_index != -1
    script_map_array[last_auto_index].concat(objs)
    script_map_array[script_map_array.size - 1] = []
  else
    script_map_array[script_map_array.size - 1] = [].concat(objs)
  end
  
  script_map_array
end