Last active
October 11, 2021 14:23
-
-
Save evaporei/5a4ed304a06f5458039d907e69a21f22 to your computer and use it in GitHub Desktop.
JS contiguous array chunks
This file contains hidden or 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 getChunk = (arr, from, size) => { | |
const clampedFrom = (from + size) > arr.length | |
// Trying to get chunk bigger than end of array. | |
// Here we reduce `from` so that the chunk size is always preserved. | |
? arr.length - size | |
: from | |
return arr.slice(clampedFrom, from + size) | |
} | |
const array = [1,2,3,4,5] | |
const chunkSize = 2 | |
const result = array | |
.map((item, index) => getChunk(array, index, chunkSize)) | |
// This is needed to remove extra pair. | |
// This pair happens because the result array should be of size equal | |
// to input.length - 1. | |
// Example: | |
// input: [1, 2, 3] (length = 3) | |
// output: [[1,2], [2,3]] (length = 2) | |
result.pop() | |
console.log('result', result) | |
// result [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oops there's a bug of a double item in the end (two 4,5), I'm gonna fix that tomorrow.