def nth_child(a, b, of_type, reverse)
return lambda { |element| false } if a == 0 && b == 0
return lambda { |element| false } if a < 0 && b < 0
b = a + b + 1 if b < 0
b -= 1 unless b == 0
lambda do |element|
return false unless element.parent && element.parent.tag?
index = 0
siblings = element.parent.children
siblings = siblings.reverse if reverse
name = of_type ? element.name : nil
found = false
for child in siblings
if child.tag? && (name == nil || child.name == name)
if a == 0
if index == b
found = child.equal?(element)
break
end
elsif a < 0
break if index > b
if child.equal?(element)
found = (index % a) == 0
break
end
else
if child.equal?(element)
found = (index % a) == b
break
end
end
index += 1
end
end
found
end
end