UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

45 lines (44 loc) 1.35 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.chunk = void 0; const slice_1 = __importDefault(require("./slice")); const toInteger_1 = __importDefault(require("./toInteger")); /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @since 5.18.0 * @category Array * @param array The array to process. * @param size The length of each chunk, default is 1 * @returns Returns the new array of chunks. * @example * * ```js * chunk(['a', 'b', 'c', 'd'], 2) * // => [['a', 'b'], ['c', 'd']] * * chunk(['a', 'b', 'c', 'd'], 3) * // => [['a', 'b', 'c'], ['d']] * ``` */ function chunk(array, size = 1) { size = Math.max((0, toInteger_1.default)(size), 0); const length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } let index = 0; let resIndex = 0; const result = new Array(Math.ceil(length / size)); while (index < length) { result[resIndex++] = (0, slice_1.default)(array, index, (index += size)); } return result; } exports.chunk = chunk; exports.default = chunk;