Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/arrayf/arrayf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,38 @@ export class arrayf {
return output;
}

/**
* Splits an array by a given split value. Useful when casting to string
* for splitting won't cut it, such as when dealing with objects.
*
* ```
* const a = {};
* const b = {};
* const c = {};
* arrayf.split([a,b,c], b); // Returns [[a], [c]];
* arrayf.split([a,b,c,b,c], b); // Returns [[a], [c], [c]];
* arrayf.split([a,b,c,b,c], b, 1); // Returns [[a], [c, b, c]];
* ```
*/
static split<T>(
values: T[],
splitValue: T,
limit: number = Number.POSITIVE_INFINITY
): T[][] {
let remainder = values;
const result = [];

while (remainder.indexOf(splitValue) !== -1 && result.length < limit) {
const splitPosition: number = remainder.indexOf(splitValue);
const splitPiece: T[] = remainder.slice(0, splitPosition);
remainder = remainder.slice(splitPosition + 1);
result.push(splitPiece);
}

}
if (result.length < limit) {
result.push(remainder);
}

return result;
}
}