Skip to content

Instantly share code, notes, and snippets.

@haampie
Created April 14, 2020 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haampie/b95dd4b81e723fddda1dcf0e383f31ca to your computer and use it in GitHub Desktop.
Save haampie/b95dd4b81e723fddda1dcf0e383f31ca to your computer and use it in GitHub Desktop.
sort_cache_by.jl
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
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