Created
March 14, 2025 07:01
-
-
Save schmichri/c6945cf08a3517c0cb1dac1b7064be51 to your computer and use it in GitHub Desktop.
Typescript Array Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Shuffles the elements of an array in place using the Fisher-Yates algorithm. | |
| * | |
| * @param {T[]} array - The array to be shuffled. | |
| * @return {T[]} The shuffled array. | |
| */ | |
| export function shuffleArray<T>(array: T[]): T[] { | |
| for (let i = array.length - 1; i > 0; i--) { | |
| const j = Math.floor(Math.random() * (i + 1)); | |
| [array[i], array[j]] = [array[j], array[i]]; | |
| } | |
| return array; | |
| } | |
| /** | |
| * Splits an array into smaller arrays of a specified size. | |
| * | |
| * @param {T[]} array - The array to split into chunks. | |
| * @param {number} chunkSize - The size of each chunk. Must be greater than 0. | |
| * @return {T[][]} A new array containing the chunks as subarrays. | |
| */ | |
| export function chunkArray<T>(array: T[], chunkSize: number): T[][] { | |
| const chunks: T[][] = []; | |
| for (let i = 0; i < array.length; i += chunkSize) { | |
| chunks.push(array.slice(i, i + chunkSize)); | |
| } | |
| return chunks; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used on https://www.license-token.com/wiki on import and display