Skip to content

Commit

Permalink
feat: add support for weakmap et weakset
Browse files Browse the repository at this point in the history
  • Loading branch information
christophehurpeau committed Aug 15, 2024
1 parent 1c5b35c commit 274fe7c
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ declare const deepFreeze: DeepFreezeExport;

export = deepFreeze;
export as namespace deepFreeze;
export { deepFreeze };
8 changes: 8 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ export function deepFreeze(obj) {
function () {
throw new Error("set is read-only");
};
} else if (obj instanceof WeakSet) {
obj.add = obj.delete = function () {
throw new Error("WeakSet is read-only");
};
} else if (obj instanceof WeakMap) {
obj.set = obj.delete = function () {
throw new Error("WeakMap is read-only");
};
}

// Freeze self
Expand Down
25 changes: 25 additions & 0 deletions lib/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@ test("freeze set", () => {
);
});

test("freeze WeekSet", () => {
const obj = deepFreeze({
weakSet: new WeakSet([{}, {}]),
});
assert.throws(
() => {
obj.weakSet.add({});
},
{ message: "WeakSet is read-only" },
);
});

test("freeze WeekMap", () => {
const obj = deepFreeze({
weakMap: new WeakMap([[{}, {}]]),
});
assert.throws(
() => {
obj.weakMap.set({}, {});
},
{ message: "WeakMap is read-only" },
);
});

test("freeze function", () => {
const mockFn = function () {};

Expand All @@ -48,6 +72,7 @@ test("freeze function", () => {

assert.throws(
() => {
// @ts-ignore
obj.fn.something = "";
},
{ message: "Cannot add property something, object is not extensible" },
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@
"@pob/commitlint-config"
]
},
"pob": {},
"pob": {
"typescript": "check-only"
},
"prettier": "@pob/root/prettier-config",
"devDependencies": {
"@pob/commitlint-config": "7.0.0",
Expand Down
12 changes: 12 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": [
"@pob/root/tsconfigs/base.json",
"@pob/root/tsconfigs/targets/node-18.json"
],
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["lib/**/*.js"]
}

0 comments on commit 274fe7c

Please sign in to comment.