Last active
December 18, 2020 14:54
-
-
Save srph/e10a1db7537e67ba4525239c2038f44e to your computer and use it in GitHub Desktop.
JS: Chunk an array in a pattern (Initial implementation of https://github.com/srph/chunk-pattern)
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
/* @flow */ | |
/** | |
* Chunks an array in a specific pattern | |
* @example chunkPattern(['haha', 'haha', 'haha', 'haha', 'haha', 'haha', 'haha', 'haha', 'haha'], [2, 3]) | |
* @return Array<Array<*>> | |
*/ | |
function chunkPattern(array: Array<*>, pattern: Array<number>): Array<Array<*>> { | |
const result: Array<Array<*>> = [] | |
let patternIndex: number = 0 | |
let patternCount: number = 0 | |
array.forEach((item, i) => { | |
if (patternCount === 0) { | |
result.push([]) | |
patternIndex = clampReset(patternIndex + 1, 0, pattern.length - 1) | |
patternCount = pattern[patternIndex] | |
} | |
const last = result[result.length - 1] | |
last.push(item) | |
patternCount-- | |
}) | |
return result | |
} | |
/** | |
* If value exceeds min, assigns value to max. | |
* If value exceeds max, assigns value to min. | |
* @return {number} | |
*/ | |
function clampReset(value: number, min: number, max: number): number { | |
if (value < min) { | |
return min | |
} | |
if (value > max) { | |
return max | |
} | |
return value | |
} | |
console.log( | |
chunkPattern(['haha', 'haha', 'haha', 'haha', 'haha', 'haha', 'haha', 'haha', 'haha'], [2, 3]) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment