Skip to content

Instantly share code, notes, and snippets.

@himelnagrana
Last active September 3, 2021 11:45
Show Gist options
  • Save himelnagrana/968c93f98e4530e853173c993a826d4b to your computer and use it in GitHub Desktop.
Save himelnagrana/968c93f98e4530e853173c993a826d4b to your computer and use it in GitHub Desktop.
a typescript utility class with some basic checks
export class Utils {
static maxItemOfArray = (arr: any) => [...arr].sort((a, b) => b - a).slice(0, 1)[0];
static areAllEqual = (array: any) => array.every((item: any) => item === array[0]);
static averageOf = (...numbers: any) => numbers.reduce((a: any, b: any) => a + b, 0) / numbers.length;
static intersection = (arr1: number[], arr2: number[]) => arr1.filter(num => arr2.includes(num));
// following will be applicable only if the arrays are sorted
static intersectionPerformant = (arr1: number[], arr2: number[]) => {
let output:number[] = [];
while( a.length > 0 && b.length > 0 ) {
if (a[0] < b[0]) {
a.shift();
} else if (a[0] > b[0]){
b.shift();
} else {
output.push(a.shift());
b.shift();
}
}
return output;
}
static reverseString = (str: string) => [...str].reverse().join('');
static sumOf = (...numbers: number[]) => numbers.reduce((a, b) => a + b, 0);
static findAndReplace = (str: string, wordToFind: string, wordToReplace: string) => str.split(wordToFind).join(wordToReplace);
static RGBToHex = (r: number, g: number, b: number) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
static shuffle = ([...array]) => {
let m = array.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[array[m], array[i]] = [array[i], array[m]];
}
return array;
};
static removeFalseValues = (arr: any) => arr.filter((item: any) => item);
static removeDuplicatedValues = (arr: any) => [...new Set(arr)];
static getTimeFromDate = (date: Date) => date.toTimeString().slice(0, 8);
static capitalizeAllWords = (str: string) => str.replace(/\b[a-z]/g, char => char.toUpperCase());
static isValidJSON = (str: string): boolean => {
try {
JSON.parse(str);
return true;
} catch (error) {
return false;
}
};
static toWords = (str: string, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(item => item);
static isValidNumber = (n: any) => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) === n;
}
@himelnagrana
Copy link
Author

iStock-504779842 1

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