Files
xo-cash-utils/source/misc.ts
T
2026-09-17 07:51:48 +00:00

52 lines
1.5 KiB
TypeScript

import type { DeeplyReadonly } from './types';
/**
* Recursively freezes an object by iterating over all properties and freezing them.
* @param obj - The object to freeze.
* @returns The frozen object.
*/
export const deepFreeze = <T>(value: T): DeeplyReadonly<T> => {
if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
for (const key of Reflect.ownKeys(value)) {
const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
if (descriptor && 'value' in descriptor) {
deepFreeze(descriptor.value);
}
}
Object.freeze(value);
}
return value;
};
/**
* Validate the value is within the bounds, returning true if it is within the bounds, false otherwise
*
* @param value - The value to validate
* @param min - The minimum value
* @param max - The maximum value
*
* @returns True if the value is within the bounds, false otherwise
*/
export const isWithinBounds = (value: number, min: number, max: number): boolean => {
if (value < min || value > max) {
return false;
}
return true;
};
/**
* Converts a non-error to an error
* @param error - The error to convert
* @returns The error
*/
export const normalizeError = (error: unknown): Error => {
// Convert the error to an error if it is not already an error
const errorInstance = error instanceof Error ? error : new Error(`${error}`);
return errorInstance;
};