Created
April 14, 2020 11:05
-
-
Save haampie/b95dd4b81e723fddda1dcf0e383f31ca to your computer and use it in GitHub Desktop.
sort_cache_by.jl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Base: getindex, setindex, length, isless | |
struct SortPair{A,B} | |
x::A | |
mapped::B | |
end | |
struct SortCache{A,B,AV,BV} <: AbstractVector{SortPair{A,B}} | |
xs::AV | |
mapped::BV | |
function SortCache(xs::AbstractVector{T}, f) where T | |
mapped = map(f, xs) | |
new{T,eltype(mapped),typeof(xs),typeof(mapped)}(xs, mapped) | |
end | |
end | |
Base.size(xs::SortCache) = size(xs.xs) | |
Base.@propagate_inbounds function Base.getindex(xs::SortCache, i::Int) | |
return SortPair(xs.xs[i], xs.mapped[i]) | |
end | |
Base.@propagate_inbounds function Base.setindex!(xs::SortCache, v::SortPair, i::Int) | |
xs.xs[i] = v.x | |
xs.mapped[i] = v.mapped | |
return v | |
end | |
Base.isless(lhs::SortPair, rhs::SortPair) = isless(lhs.mapped, rhs.mapped) | |
function sort_with_cached_by(xs; by = identity) | |
sort!(SortCache(xs, by)) | |
return xs | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sort_with_cached_by(rand(Int, 100), by = abs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment