Skip to content

Instantly share code, notes, and snippets.

Keybase proof

I hereby claim:

  • I am koos42 on github.
  • I am koos42 (https://keybase.io/koos42) on keybase.
  • I have a public key ASCd1eCAzk4EyQYOvH5zn9CDutJ7ZmiKNJl5aFURYyUbrAo

To claim this, I am signing this object:

@koos42
koos42 / stable_group_by.ex
Created May 27, 2016 20:50
implements a stable group_by in O(n)
defmodule Example do
@doc """
iex> stable_group_by([c: 1, b: 1, b: 2, b: 3, a: 1, a: 2, a: 3], &elem(&1, 0))
%{a: [a: 1, a: 2, a: 3], b: [b: 1, b: 2, b: 3], c: [c: 1]}
"""
def stable_group_by(list, mapper_fun) do
list
|> Enum.reduce(%{}, fn(item, acc) ->
Map.update(acc, mapper_fun.(item), [item], fn(sub_list)-> [ item | sub_list ] end)
end)
@koos42
koos42 / grouper.rb
Created January 6, 2012 23:52
Jesse challenges: Do my homework. Write a method that takes an array of elements where each element is either of type A or type B and returns an array of arrays where all the sub arrays are filled with only type A or type B and preserve the order.
# Do my homework:
# Write a method that takes an array of elements where each element is either of
# type A or type B and returns an array of arrays where all the sub arrays are
# filled with only type A or type B and preserve the order.
# example: [a, a, b, a, a, a, b, b, a] => [[a, a], [b], [a, a, a], [b, b], [a]]
# these solutions don't enforce the constraint that there be only two types of things.
# group things