Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swap! #3

Merged
merged 1 commit into from
Sep 28, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/IndexedArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,24 @@ end

copy{T}(ia::IndexedArray{T}) = IndexedArray{T}(copy(ia.items))

export AbstractIndexedArray, IndexedArray, IndexedArrayError, findfirst!
"`swap!(ia::IndexedArray, to::Int, from::Int)` interchange/swap the values on the indices `to` and `from` in the `IndexedArray`"
function swap!(ia::IndexedArray, to::Int, from::Int)
if to == from
checkbounds(ia,to)
return ia
end
previous_id = ia[to]
future_id = ia[from]

ia.items[to] = future_id
ia.items[from] = previous_id

ia.lookup[previous_id] = from
ia.lookup[future_id] = to

return ia
end

export AbstractIndexedArray, IndexedArray, IndexedArrayError, findfirst!, swap!

end # module
17 changes: 17 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ ia2 = copy(ia)
@test ia2[:] == ["cat", "dog", "mouse"]
@test findfirst(ia2, "cat") == 1

let ia = IndexedArray(["cat", "dog", "mouse", "human"]), original = copy(ia)

ia = swap!(ia, 2, 2)

@test ia == original
@test_throws BoundsError swap!(ia, 5, 5)

swap!(ia, 2, 3)

@test findfirst(ia, "mouse") == 2
@test findfirst(original, "mouse") == 3

@test findfirst(ia, "dog") == 3
@test findfirst(original, "dog") == 2
end


Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Can you switch to a four-space indent and also get rid of the added newline at the end of the file?

I think it would also be good to have a test for when to == from. Perhaps the function itself should special-case for this and return immediately as well.

# setindex!

# indexin, findin
Expand Down