Skip to content

Instantly share code, notes, and snippets.

@sethdavis512
Last active March 23, 2025 20:16
Show Gist options
  • Save sethdavis512/f21c268084e64feb64686b6a869697bc to your computer and use it in GitHub Desktop.
Save sethdavis512/f21c268084e64feb64686b6a869697bc to your computer and use it in GitHub Desktop.
function getSafe(fn) {
try {
return fn();
} catch (e) {
return undefined;
}
}
/**
* Safely retrieves a value from an object at the specified path.
*
* @param obj - The object to retrieve the value from.
* @param path - The path to the property as a string or an array of strings.
* @param defValue - The default value to return if the property is not found.
* @returns The value at the specified path or the default value.
*/
// https://youmightnotneed.com/lodash#get
function get<T, R = unknown>(
obj: T,
path: string | string[] | undefined,
defValue: R
): R | unknown {
// If path is not defined or has a false value
if (!path) return undefined;
// Convert the path to an array if it is a string
const pathArray = Array.isArray(path) ? path : path.match(/([^[.\]])+/g);
// If the path cannot be parsed, return the default value
if (!pathArray) return defValue;
// Use reduce to traverse the object along the path
const result = pathArray.reduce(function (prevObj: any, key: string) {
return prevObj && key in prevObj ? prevObj[key] : undefined;
}, obj);
// Return the result or the default value if the result is undefined
return result === undefined ? defValue : result;
}
function allTrue(conditions: boolean[]): boolean {
return conditions.every(Boolean);
}
function someTrue(conditions: boolean[]): boolean {
return conditions.some(Boolean);
}
function doesStringInclude(
searchString: string,
inclusionList: Array<string>
) {
return inclusionList.length === 0 || searchString === ''
? false
: !!inclusionList.find((iteratee) => searchString.includes(iteratee));
}
function getUniqueId(
prefix: string = "my-prefix",
length: number = 8,
characters: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
): string {
const hash = Array.from({ length }, () =>
characters.charAt(Math.floor(Math.random() * characters.length))
).join("");
return `${!!prefix ? `${prefix}-` : ''}${hash}`;
}
function getRandomBool(chance: number = 50) {
return Math.round(Math.random() * 100) >= chance;
}
function pickRandom(arr) {
return arr[Math.floor(Math.random() * arr.length)]
};
function buildMockArray<T>(content: T, num: number): T[] {
return Array(num).fill(null).map(() => content);
}
// ==============================================
async function encryptData(data, key) {
const encodedData = new TextEncoder().encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12)); // Initialization vector
const encryptedData = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encodedData
);
return { iv, encryptedData };
}
async function decryptData(encryptedData, key, iv) {
const decryptedData = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encryptedData
);
return new TextDecoder().decode(decryptedData);
}
async function generateKey() {
return await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
}
// Example usage
// (async () => {
// const key = await generateKey();
// const data = "Hello, World!";
// const { iv, encryptedData } = await encryptData(data, key);
// console.log("Encrypted Data:", new Uint8Array(encryptedData));
// const decryptedData = await decryptData(encryptedData, key, iv);
// console.log("Decrypted Data:", decryptedData);
// })();
// ==============================================
function getEnvVariable(key: string): string {
if (key === undefined) {
throw Error(`"${key}" is undefined`);
}
const value = process.env[key];
if (!value) {
throw Error(
`Environment variable "${key}" does not exist on process.env`
);
}
return value;
}
// ==============================================
// Building-blocks to use for composition
const double = x => x + x;
const triple = x => 3 * x;
const quadruple = x => 4 * x;
// Function composition enabling pipe functionality
const pipe = (...fns) => input => [...fns].reduce((acc, fn) => fn(acc), input);
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
// ==============================================
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
});
const formatToDollar = (n: number) => formatter.format(n); // Example number
console.log(formatToDollar(1234.5)); // Outputs: $1,234.50
const getRandomDate = (start: Date, end: Date) =>
new Date(
start.getTime() + Math.random() * (end.getTime() - start.getTime())
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment