Skip to content

Instantly share code, notes, and snippets.

@compwron
Created June 7, 2019 03:09
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 compwron/1d2e3ac7209658f66fd7b2d57eccbfd4 to your computer and use it in GitHub Desktop.
Save compwron/1d2e3ac7209658f66fd7b2d57eccbfd4 to your computer and use it in GitHub Desktop.
# group by x
# def time(a_proc)
# start = Time.now
# a_proc.call
# puts Time.now - start
# end
#
# time(Proc.new { code_here })
# time(Proc.new { more_code_here })
# {'John' => [..], 'Linda' => [..]}
def group_by(data, key)
data.each_with_object({ grouped_data: {}, problems: {} }) do |datum, acc|
key_value = datum[key]
if key_value == nil
problem_key = "missing_#{key}"
acc[:problems][problem_key] ||= []
acc[:problems][problem_key] << datum
next
end
acc[:grouped_data][key_value] ||= []
acc[:grouped_data][key_value] << datum
acc
end
end
# p group_by([{ name: 'John' }, { name: 'Linda' }, { name: 'Linda' }, { a: 1 }], :name)
# {:grouped_data=>{"John"=>[{:name=>"John"}], "Linda"=>[{:name=>"Linda"}, {:name=>"Linda"}]}, :problems=>{"missing_name"=>[{:a=>1}]}}
# sliding window
def sliding_window(list, count)
(0..list.size - count).map do |idx|
# if idx + count >= list.size
list[idx...(idx + count)]
end
end
p sliding_window([1, 2, 3, 4], 2)
p sliding_window([1, 2, 3, 4], 3)
# [[1, 2, 3], [2, 3, 4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment