Skip to content

Instantly share code, notes, and snippets.

@wvovaw
Last active July 21, 2024 15:00
Show Gist options
  • Save wvovaw/80716ab93d16d42f390ece8c6ace3e5a to your computer and use it in GitHub Desktop.
Save wvovaw/80716ab93d16d42f390ece8c6ace3e5a to your computer and use it in GitHub Desktop.
Some JS and TS code snippets that I need to use sometimes
// Generate random string
export const generateUID = (length: number) =>
Array(length)
.fill("")
.map((v) => Math.random().toString(36).charAt(2))
.join("");
// Convert ArrayBuffer to HEX string
export const bytesToHEX = (bytes: ArrayBuffer) =>
Array.from(new Uint8Array(bytes)).map(b => b.toString(16).padStart(2, '0')).join('');
// Date string in RU format with timezone
export const date = new Date()
.toLocaleString("ru-RU", { timeZone: "Europe/Moscow" })
.replaceAll("/", ".")
.split(",")[0];
/**
* Checks if string is an isogram (if it has only unique chars)
* @param str string to check
* @returns boolean true if the string is isogram, false otherwise
*/
export function isIsogram(str: string): boolean {
return !/(\w).*\1/.test(str);
}
/**
* Group array of objects by given keys
* @param keys keys to be grouped by
* @param array objects to be grouped
* @returns an object with objects in `array` grouped by `keys`
* @see <https://gist.github.com/mikaello/06a76bca33e5d79cdd80c162d7774e9c>
*/
export const groupBy = <T>(keys: (keyof T)[]) => (array: T[]): Record<string, T[]> =>
array.reduce((objectsByKeyValue, obj) => {
const value = keys.map((key) => obj[key]).join('-');
objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
return objectsByKeyValue;
}, {} as Record<string, T[]>);
/**
* Generates SHA-256 string for provided string
* @param str payload data
* @returns hash string in promise
*/
export async function SHA256(str: string): Promise<string> {
const encoder = new TextEncoder();
const blockDataBuffer = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest("SHA-256", blockDataBuffer);
const hashString = Array.from(new Uint8Array(hashBuffer)).map((b) =>
b.toString(16).padStart(2, "0");
).join("");
return hashString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment