Skip to content

Instantly share code, notes, and snippets.

@DarkRoku12
Created May 21, 2025 21:31
Show Gist options
  • Select an option

  • Save DarkRoku12/58293f7a2d12242cf3633dae5088c6a8 to your computer and use it in GitHub Desktop.

Select an option

Save DarkRoku12/58293f7a2d12242cf3633dae5088c6a8 to your computer and use it in GitHub Desktop.
General JS/TS utility functions.
/***
General utility functions by @DarkRoku12
***/
export async function batch_await_fn<T extends any[], R>( iArray: T, batchLen: number, fn: ( chunk: T ) => Promise<R | R[]> )
{
const results = [] as R[];
for ( let i = 0; i < iArray.length; i += batchLen )
{
const chunk = iArray.slice( i, i + batchLen ) as T;
const checkResults = await fn( chunk );
if ( Array.isArray( checkResults ) ) results.push( ...checkResults );
else results.push( checkResults );
}
return results;
}
/** Convert an array<T> into chunks: array<T[]> */
export function in_chunks<T extends any[]>( iArray: T, chunkLen: number )
{
const chunks = [] as T[];
for ( let i = 0; i < iArray.length; i += chunkLen )
{
const chunk = iArray.slice( i, i + chunkLen ) as T;
chunks.push( chunk );
}
return chunks;
}
export async function batch_await<T extends Promise<any>>( iArray: T[], batchLen: number )
{
return batch_await_fn( iArray, batchLen, ( chunk ) => Promise.all( chunk ) );
}
export type STRIP_COMMON_PROPS = "password" | "created_at" | "updated_at" | "synced_at" | "deleted_at";
/** Strip common properties from an object. */
export function strip<T extends Record<any, any>, P extends Readonly<Array<keyof T>> = []>(
obj: T,
props?: P,
defaults?: boolean,
): Omit<T, STRIP_COMMON_PROPS | P[number]>
{
const defProps = ["password", "created_at", "updated_at", "deleted_at", "synced_at"] as const;
const delProps = [...( defaults ? defProps : [] ), ...( props || [] )];
for ( const prop of delProps ) delete obj[prop];
return obj as Omit<T, STRIP_COMMON_PROPS | P[number]>;
}
/** Strip common properties from an object (copy). */
export function copy_strip( obj: Record<any, any> )
{
return strip( { ...obj } );
}
/** Pick properties from an object. */
export function pick<T extends Record<any, any>, P extends Readonly<Array<keyof T>> = []>( obj: T, props: P ): Pick<T, P[number]>
{
const newObj = {} as Pick<T, P[number]>;
for ( const prop of props ) newObj[prop] = obj[prop];
return newObj;
}
/** Make an array unique (copy). */
export function unique<T>( array: T[] )
{
return [...new Set( array )];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment