Last active
September 12, 2018 21:33
-
-
Save jamesdaniels/8e91bfd3acb92c3e21e63332cc9fac4f to your computer and use it in GitHub Desktop.
javascript implementation of https://www.rubydoc.info/stdlib/core/Enumerable:chunk_while
This file contains 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
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]] | |
, []) |
This file contains 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
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