Skip to content

Instantly share code, notes, and snippets.

@tilgovi
Created June 30, 2011 23:50
Show Gist options
  • Select an option

  • Save tilgovi/1057573 to your computer and use it in GitHub Desktop.

Select an option

Save tilgovi/1057573 to your computer and use it in GitHub Desktop.
chunkify(InList, BaseChunkSize) ->
%%io:format("length of list is ~p and chunk size is ~p ~n",[length(InList),BaseChunkSize]),
case byte_size(term_to_binary(InList)) of
Size when Size > BaseChunkSize ->
NumberOfChunksLikely = ((Size div BaseChunkSize) + 1),
ChunkThreshold = Size div NumberOfChunksLikely,
chunkify(InList, ChunkThreshold, [], 0, []);
_Else ->
[InList]
end.
chunkify([], _ChunkThreshold, [], 0, OutputChunks) ->
lists:reverse(OutputChunks);
chunkify([], _ChunkThreshold, OutList, _OutListSize, OutputChunks) ->
lists:reverse([lists:reverse(OutList) | OutputChunks]);
chunkify([InElement | RestInList], ChunkThreshold, OutList, OutListSize, OutputChunks) ->
case byte_size(term_to_binary(InElement)) of
Size when (Size + OutListSize) > ChunkThreshold andalso OutList /= []
andalso length(OutList) > 9 ->
{Left, Right} = lists:split(length(OutList)/2, OutList),
chunkify(RestInList, ChunkThreshold, [], 0, [lists:reverse([InElement | Right]) | lists:reverse(Left, OutputChunks)]);
Size ->
chunkify(RestInList, ChunkThreshold, [InElement | OutList], OutListSize + Size, OutputChunks)
end.
@bdionne
Copy link
Copy Markdown

bdionne commented Jul 1, 2011

I need a second cup of coffee to unravel all these reversals

@tilgovi
Copy link
Copy Markdown
Author

tilgovi commented Jul 1, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment