ts-utls
Version:
Utilities for TypeScript library
71 lines (67 loc) • 2.86 kB
JavaScript
;
/*
MIT License
Copyright (c) 2020 Cyril Dever
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.range = exports.groupBy = exports.flatten = exports.chunk = void 0;
/**
* Split an array into chunks of the passed size
*
* @param {T[]} arr - The array to split
* @param {number} chunkSize - The maximum size of chunks
* @returns the chunked array of arrays
*/
const chunk = (arr, chunkSize) => arr.reduce((segments, _, idx) => idx % chunkSize === 0
? [...segments, arr.slice(idx, idx + chunkSize)]
: segments, new Array());
exports.chunk = chunk;
/**
* Flatten an array of arrays of items into an array of items
*
* @param {T[][]} arrs - The array of arrays to flatten
* @returns the flattened array of items
*/
const flatten = (arrs) => [].concat(...arrs);
exports.flatten = flatten;
/**
* Group an array of objects by some field acting as key
*
* @param {T[]} arr - The array of objects
* @param {K} key - The key to use
* @returns the map array grouped by key
*/
const groupBy = (arr, key) => arr.reduce((acc, obj) => {
const v = obj[key];
acc[v] = (acc[v] || []).concat(obj); // eslint-disable-line @typescript-eslint/strict-boolean-expressions
return acc;
}, {});
exports.groupBy = groupBy;
/**
* Returns a range of integers
*
* It is the equivalent of a for-loop with `i = start` and `i < start + size` with `i = i + step` at the end of each round
*
* @param {number} start - The starting point
* @param {number} end - The number of items to return (not included)
* @param {number} step - The (optional) step size between numbers (Default: 1)
* @returns the array of integers
*/
const range = (start, end, step = 1) => [...Array(Math.ceil(end / step)).keys()].map(i => i * step + start);
exports.range = range;
//# sourceMappingURL=array.js.map