Skip to content

Instantly share code, notes, and snippets.

@schmichri
Created March 14, 2025 07:01
Show Gist options
  • Select an option

  • Save schmichri/c6945cf08a3517c0cb1dac1b7064be51 to your computer and use it in GitHub Desktop.

Select an option

Save schmichri/c6945cf08a3517c0cb1dac1b7064be51 to your computer and use it in GitHub Desktop.
Typescript Array Helper
/**
* 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;
}
@schmichri
Copy link
Author

Used on https://www.license-token.com/wiki on import and display

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment