Deeply freeze object
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { DeeplyReadonly } from "./types";
|
||||
|
||||
/**
|
||||
* Validate the value is within the bounds, returning true if it is within the bounds, false otherwise
|
||||
*
|
||||
@@ -30,3 +32,27 @@ export const tryAsync = async (fn: () => unknown, onError?: (error: Error) => vo
|
||||
onError?.(errorInstance);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user