Skip to content

Instantly share code, notes, and snippets.

@Vehmloewff
Last active December 19, 2020 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vehmloewff/74851dd58c1ee9eddf0229967d71d68e to your computer and use it in GitHub Desktop.
Save Vehmloewff/74851dd58c1ee9eddf0229967d71d68e to your computer and use it in GitHub Desktop.

Some helper functions that can come in handy day to day.

export const asyncForEach = async <T>(arr: T[], cb: (item: T, index: number) => Promise<void> | void) => {
for (let index = 0; index < arr.length; index++) await cb(arr[index], index);
};
export const makeArray = <T>(val: T | T[]) => (Array.isArray(val) ? val : [val]);
export const callIfFunction = <T, A>(item: T | ((...args: A[]) => T), val: A[]): T => {
// @ts-ignore
if (typeof item === 'function') return item(...val);
return item;
};
export const removeArrayDuplicates = <T>(arr: T[]): T[] => {
return [...new Set(arr)];
};
export function numDigits(n: number) {
return (Math.log10((n ^ (n >> 31)) - (n >> 31)) | 0) + 1;
}
export const repeat = (num: number, cb: (index: number) => void) => {
for (let index = 0; index < num; index++) cb(index);
};
export const multiplyString = (str: string, times: number) => {
let result = ``;
repeat(times, () => (result += str));
return result;
};
export const isOk = (v: any) => {
return v !== undefined && v !== null;
};
export const lastItem = <T>(arr: T[]): T => {
return arr[arr.length - 1];
};
export const flattenArray = <T>(arr: T[][]): T[] => {
const flattened: T[] = [];
arr.forEach(i => flattened.push(...i));
return flattened;
};
export function lazyJSONParse(json: string): any {
try {
return JSON.parse(json)
} catch (e) {
return {}
}
}
export function delay(time: number) {
return new Promise<void>(resolve => {
setTimeout(() => resolve(), time)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment