2018-03-26 19:05:30 +02:00
|
|
|
module Util
|
2017-09-08 12:10:22 +02:00
|
|
|
module List
|
|
|
|
|
|
|
|
# set the next instruction (also aliased as <<)
|
|
|
|
# throw an error if that is set, use insert for that use case
|
|
|
|
# return the instruction, so chaining works as one wants (not backwards)
|
2018-03-11 11:41:15 +01:00
|
|
|
def set_next( nekst )
|
2017-09-08 12:10:22 +02:00
|
|
|
raise "Next already set #{@next}" if @next
|
|
|
|
@next = nekst
|
|
|
|
nekst
|
|
|
|
end
|
|
|
|
|
|
|
|
# get the next instruction (without arg given )
|
|
|
|
# when given an interger, advance along the line that many time and return.
|
|
|
|
def next( amount = 1)
|
|
|
|
(amount == 1) ? @next : @next.next(amount-1)
|
|
|
|
end
|
|
|
|
|
|
|
|
# set the give instruction as the next, while moving any existing
|
|
|
|
# instruction along to the given ones's next.
|
|
|
|
# ie insert into the linked list that the instructions form
|
2018-03-18 06:06:01 +01:00
|
|
|
# but allowing the instruction to be a list too (ie more than one)
|
2018-03-11 11:41:15 +01:00
|
|
|
def insert( instruction )
|
2018-04-08 17:52:17 +02:00
|
|
|
raise "circular insert #{instruction}" if instruction == self
|
2018-03-18 06:06:01 +01:00
|
|
|
instruction.last.set_next @next
|
2018-03-19 08:35:08 +01:00
|
|
|
@next = instruction
|
2017-09-08 12:10:22 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
# return last set instruction. ie follow the linked list until it stops
|
|
|
|
def last
|
|
|
|
code = self
|
2018-04-06 19:20:39 +02:00
|
|
|
while( code.next )
|
2018-04-06 19:55:21 +02:00
|
|
|
raise "Circular list #{code.class}:#{code}" if code == code.next
|
2018-04-06 19:20:39 +02:00
|
|
|
code = code.next
|
|
|
|
end
|
2017-09-08 12:10:22 +02:00
|
|
|
return code
|
|
|
|
end
|
|
|
|
|
|
|
|
# set next for the last (see last)
|
|
|
|
# so append the given code to the linked list at the end
|
2018-03-11 11:41:15 +01:00
|
|
|
def append( code )
|
2017-09-08 12:10:22 +02:00
|
|
|
last.set_next code
|
2018-03-15 17:24:03 +01:00
|
|
|
self
|
2017-09-08 12:10:22 +02:00
|
|
|
end
|
2018-03-15 16:10:21 +01:00
|
|
|
alias :<< :append
|
2017-09-08 12:10:22 +02:00
|
|
|
|
2018-03-26 13:54:41 +02:00
|
|
|
def length
|
|
|
|
ret = 0
|
|
|
|
self.each { ret += 1}
|
2017-09-08 12:10:22 +02:00
|
|
|
ret
|
|
|
|
end
|
|
|
|
|
2018-03-26 13:54:41 +02:00
|
|
|
def each(&block)
|
|
|
|
block.call(self)
|
|
|
|
@next.each(&block) if @next
|
|
|
|
end
|
|
|
|
|
2017-09-08 12:10:22 +02:00
|
|
|
end
|
|
|
|
end
|