Skip to content

Commit b54021d

Browse files
committed
feat: add deepFreeze function and corresponding tests for object immutability
1 parent 2677c07 commit b54021d

File tree

2 files changed

+72
-3
lines changed

2 files changed

+72
-3
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { deepFreeze } from './deepFreeze';
2+
3+
describe('deepFreeze', () => {
4+
it('should deeply freeze an object', () => {
5+
const obj = {
6+
a: 1,
7+
b: {
8+
c: 2,
9+
d: {
10+
e: 3,
11+
},
12+
},
13+
};
14+
15+
const frozenObj = deepFreeze(obj);
16+
17+
expect(Object.isFrozen(frozenObj)).toBe(true);
18+
expect(Object.isFrozen(frozenObj.b)).toBe(true);
19+
expect(Object.isFrozen(frozenObj.b.d)).toBe(true);
20+
});
21+
22+
it('should not allow modification of a deeply frozen object', () => {
23+
const obj = {
24+
a: 1,
25+
b: {
26+
c: 2,
27+
d: {
28+
e: 3,
29+
},
30+
},
31+
};
32+
33+
const frozenObj = deepFreeze(obj);
34+
35+
expect(() => {
36+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
37+
// @ts-ignore
38+
frozenObj.a = 2;
39+
}).toThrow(TypeError);
40+
41+
expect(() => {
42+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
43+
// @ts-ignore
44+
frozenObj.b.c = 3;
45+
}).toThrow(TypeError);
46+
47+
expect(() => {
48+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
49+
// @ts-ignore
50+
frozenObj.b.d.e = 4;
51+
}).toThrow(TypeError);
52+
});
53+
54+
it('should return the same object reference', () => {
55+
const obj = {
56+
a: 1,
57+
b: {
58+
c: 2,
59+
d: {
60+
e: 3,
61+
},
62+
},
63+
};
64+
65+
const frozenObj = deepFreeze(obj);
66+
67+
expect(frozenObj).toBe(obj);
68+
});
69+
});

shared/validation/common/deepFreeze.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
export function deepFreeze<T extends { [key: string]: any }>(
1+
export const deepFreeze = <T extends { [key: string]: any }>(
22
object: T,
3-
): Readonly<T> {
3+
): Readonly<T> => {
44
const propNames = Object.getOwnPropertyNames(object);
55

66
for (const name of propNames) {
@@ -13,4 +13,4 @@ export function deepFreeze<T extends { [key: string]: any }>(
1313
}
1414

1515
return Object.freeze(object);
16-
}
16+
};

0 commit comments

Comments
 (0)