UNPKG

everyutil

Version:

A comprehensive library of lightweight, reusable utility functions for JavaScript and TypeScript, designed to streamline common programming tasks such as string manipulation, array processing, date handling, and more.

30 lines (29 loc) 943 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.chunkByCondition = void 0; /** * Splits an array into chunks where the provided function returns true for consecutive elements. * @author @dailker * @template T * @param {T[]} array - The input array. * @param {(a: T, b: T, idx: number, arr: T[]) => boolean} fn - Condition function, receives current and previous element. * @returns {T[][]} - Array of chunks. */ function chunkByCondition(array, fn) { if (!array.length) return []; const result = []; let chunk = [array[0]]; for (let i = 1; i < array.length; i++) { if (fn(array[i - 1], array[i], i, array)) { chunk.push(array[i]); } else { result.push(chunk); chunk = [array[i]]; } } result.push(chunk); return result; } exports.chunkByCondition = chunkByCondition;