Skip to content

Instantly share code, notes, and snippets.

@jamesdaniels
Last active September 12, 2018 21:33
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 jamesdaniels/8e91bfd3acb92c3e21e63332cc9fac4f to your computer and use it in GitHub Desktop.
Save jamesdaniels/8e91bfd3acb92c3e21e63332cc9fac4f to your computer and use it in GitHub Desktop.
const chunk_while = (input, predicate) =>
input.reduce((accumulator, current, index) =>
index > 0 && predicate(input[index-1], current) &&
[...accumulator.slice(0, accumulator.length-1), [...accumulator[accumulator.length-1], current]] ||
[...accumulator, [current]]
, [])
const chunk_while = <T>(input: Array<T>, predicate: (elt_before: T, elt_after: T) => boolean) =>
input.reduce((accumulator, current, index) =>
index > 0 && predicate(input[index-1], current) &&
[...accumulator.slice(0, accumulator.length-1), [...accumulator[accumulator.length-1], current]] ||
[...accumulator, [current]]
, [] as Array<Array<T>>)
chunk_while([1,2,1,2,2,1,1,2], x => x != 1) // => [[1], [2, 1], [2, 2, 1], [1], [2]]
chunk_while([1,2,4,9,10,11,12,15,16,19,20,21], (i, j) => i+1 == j) // => [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment