Skip to content

Instantly share code, notes, and snippets.

@jesatrix
Last active Aug 9, 2021
Embed
What would you like to do?
Random Utilities
import {
format,
formatDistanceToNow,
formatDuration,
formatISO,
intervalToDuration,
subMonths,
} from 'date-fns';
export class DateUtil {
static getUTCISODate(date: Date = new Date()) {
return formatISO(new Date(date.toUTCString()));
}
static getCountsDurations(
startTime: Date,
startingCount?: number,
endingCount?: number,
) {
const startMs = startTime.getTime();
const endTime = new Date();
const endMs = endTime.getTime();
const value = endMs - startMs;
const human = formatDuration(intervalToDuration({ start: 0, end: value }));
const estimate = formatDistanceToNow(startTime, {
includeSeconds: true,
});
const changeInPercentNumber =
startingCount && endingCount
? ((endingCount - startingCount) / endingCount) * 100
: undefined;
const changeInPercentString =
startingCount && endingCount
? `${
changeInPercentNumber > 0 ? '+' : ''
}${changeInPercentNumber.toFixed(2)} %`
: undefined;
return {
endTime,
duration: human,
durationValue: value,
human,
estimate,
changeInPercent: changeInPercentString,
changeInPercentNumber,
};
}
}
export class HttpUtils {
/**
* Find all instances of a character symbol in a string and replace them with a space
* @param strValue original string to search and update
* @param character character to search for and split on
*/
public splitByCharacterToWords(strValue: string, character: string): string {
const characterGroups = strValue.split(character);
for (let index = 0; index < characterGroups.length; index++) {
const strGroup = characterGroups[index];
const indexOfCharacter = strGroup.indexOf(character);
const updatedStrGroup =
strGroup.charAt(0).toUpperCase() + strGroup.slice(1);
characterGroups[index] =
indexOfCharacter >= 0
? updatedStrGroup.slice(0, indexOfCharacter)
: updatedStrGroup;
}
return characterGroups.join(' ');
}
/**
* Convert a camel case variable to a sentence case phrase/title
* @param strValue original string to update
*/
public camelCaseToWords(strValue: string): string {
strValue = strValue.replace(/([A-Z])/g, ' $1');
return strValue.charAt(0).toUpperCase() + strValue.slice(1);
}
/**
* Remove a symbol or character from the end of a string
* @param fullStr String to update
* @param symbol Symbol to remove from end of string
*/
public trimStringEnd(fullStr: string, symbol: string) {
if (fullStr.endsWith(symbol)) {
fullStr = fullStr.slice(0, fullStr.length - 1);
}
return fullStr;
}
/**
* Convert param string to HTTP params
* @param paramString: filter and sort parameters as a string
*/
public getHttpParams(paramString: string): HttpParams {
// Create HTTP Params
paramString = this.trimStringEnd(paramString, '&');
return new HttpParams({ fromString: paramString });
}
/**
* Get param key value URL string
* @param key Param name
* @param value Param value
*/
public getParamKeyValue(key: string, value: string | string[]) {
if (value instanceof Array) {
const valueStr = value.join(',');
return `${key}=${valueStr}&`;
} else {
return `${key}=${value}&`;
}
}
}
export class Utils {
isNotFirst(item: number, itemIndex: number) {
return item > 0 || itemIndex > 0;
}
hasNoValue(value: any) {
return ['', 'undefined', 'null', null, undefined].includes(value);
}
hasValue(value: any): boolean {
return !this.hasNoValue(value);
}
getAbbreviation = (nameValue: string): string => {
if (!this.hasValue(nameValue)) {
return '';
}
//Get the first letter of each word in the name. Convert "VisualStudio" to "VS"
const match = nameValue.match(/\b(\w)/g);
if (match) {
return match.join('').toUpperCase();
}
return '';
}
copy<T extends Record<string, any>>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}
instanceOfInterface<T>(unknownObject: any, fieldName: string): unknownObject is T {
return fieldName in unknownObject;
}
mapToProperty<T, K extends keyof T>(items: T[], key: K) {
return items.map((x) => x[key]);
}
sum(xs: number[]) {
return xs.reduce((a: number, c: number) => a + c, 0);
}
isPalindrome(val: string) {
const reverseVal = val
.split('')
.reverse()
.join('');
return val === reverseVal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment