@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
65 lines (64 loc) • 1.53 kB
JavaScript
/**
* Split an array into pages of size `countPerPage` and then get the `getPage` page from that split.
* `getPage` is `0` indexed.
*
* @category Array
* @category Package : @augment-vir/common
* @example
*
* ```ts
* import {getArrayPage} from '@augment-vir/common';
*
* const result = getArrayPage(
* [
* 'a',
* 'b',
* 'c',
* ],
* {
* countPerPage: 2,
* getPage: 1,
* },
* );
* // result is `['c']`
* ```
*/
export function getArrayPage(originalArray, options) {
const chunks = chunkArray(originalArray, { chunkSize: options.countPerPage });
return chunks[options.getPage];
}
/**
* Split an array into multiple sub array "chunks" based on the given options.
*
* @category Array
* @category Package : @augment-vir/common
* @example
*
* ```ts
* import {chunkArray} from '@augment-vir/common';
*
* const result = chunkArray(
* [
* 'a',
* 'b',
* 'c',
* ],
* {
* chunkSize: 2,
* },
* );
* // result is `[['a', 'b'], ['c']]`
* ```
*/
export function chunkArray(originalArray, options) {
const chunkSize = options.chunkSize ||
(options.chunkCount ? Math.ceil(originalArray.length / options.chunkCount) : 0);
if (!chunkSize) {
return [[...originalArray]];
}
const chunkedArray = [];
for (let i = 0; i < originalArray.length; i += chunkSize) {
chunkedArray.push(originalArray.slice(i, i + chunkSize));
}
return chunkedArray;
}