Last active
December 15, 2015 15:09
-
-
Save epitron/a1807e9148d901e4cdd8 to your computer and use it in GitHub Desktop.
Weave together multiple sorted enumerables into one sorted enumerable. (The supplied block is what to sort by, and an enumerable is returned.)
This file contains hidden or 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
def weave(*enums, &key_getter) | |
enums = enums.map { |e| e.to_enum.each } | |
Enumerator.new do |yielder| | |
while enums.any? | |
enums.sort_by! { |enum| key_getter.call(enum.peek) rescue 0 } | |
begin | |
yielder << enums.first.next | |
rescue StopIteration | |
enums.shift | |
end | |
end | |
end | |
end | |
lesspipe do |less| | |
weave(URLActivity, APIActivity) { |rec| -rec[:time] }.each do |a| | |
a.print(less) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment