Skip to content

Commit

Permalink
implement builtin swap
Browse files Browse the repository at this point in the history
  • Loading branch information
jreidinger committed Feb 5, 2013
1 parent a7ef787 commit c975a75
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/ruby/ycp/builtins.rb
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,20 @@ def self.reduce *params, &block


# Creates new list with swaped elemetns at offset i1 and i2.
def self.swap
raise "Builtin list::swap() is not implemented yet"
def self.swap list, offset1, offset2
return nil if list.nil? || offset1.nil? || offset2.nil?

return list if offset1 < 0 || offset2 >= list.size || (offset1 > offset2)

res = []
if offset1 > 0
res.concat list[0..offset1-1]
end
res.concat list[offset1..offset2].reverse!
if offset2 < list.size-1
res.concat list[offset2+1..-1]
end
return res
end
end

Expand Down
21 changes: 21 additions & 0 deletions tests/ruby/builtins_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -550,4 +550,25 @@ def test_list_reduce_2params
assert_equal 5, YCP::Builtins::List.reduce(5,[]) { |x,y| next x }
assert_equal nil, YCP::Builtins::List.reduce(nil,nil) { |x,y| next x }
end

SWAP_TESTDATA = [
[nil,nil,nil,nil],
[[0],nil,0,nil],
[[0],0,nil,nil],
[[0],0,nil,nil],
[[5,6],-1,1,[5,6]],
[[5,6],0,2,[5,6]],
[[0,1,2,3],0,3,[3,2,1,0]],
[[0,1,2,3],0,2,[2,1,0,3]],
[[0,1,2,3],1,3,[0,3,2,1]],
[[0,1,2,3],2,2,[0,1,2,3]],
]
def test_list_swap
SWAP_TESTDATA.each do |list,offset1,offset2,result|
list_prev = list.nil? ? nil : list.dup
assert_equal result, YCP::Builtins::List.swap(list, offset1, offset2)
#check that list is not modified
assert_equal list_prev, list
end
end
end

0 comments on commit c975a75

Please sign in to comment.