Skip to content

Commit b6d898e

Browse files
committed
[New] add WeakRef support
1 parent d6c5b37 commit b6d898e

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

.eslintrc

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"max-lines": 1,
99
"max-lines-per-function": 1,
1010
"max-params": [2, 4],
11-
"max-statements": [2, 100],
11+
"max-statements": 0,
1212
"max-statements-per-line": [2, { "max": 2 }],
1313
"no-magic-numbers": 0,
1414
"no-param-reassign": 1,

index.js

+16
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
1010
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
1111
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
1212
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
13+
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
14+
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
1315
var booleanValueOf = Boolean.prototype.valueOf;
1416
var objectToString = Object.prototype.toString;
1517
var functionToString = Function.prototype.toString;
@@ -173,6 +175,9 @@ module.exports = function inspect_(obj, options, depth, seen) {
173175
if (isWeakSet(obj)) {
174176
return weakCollectionOf('WeakSet');
175177
}
178+
if (isWeakRef(obj)) {
179+
return weakCollectionOf('WeakRef');
180+
}
176181
if (isNumber(obj)) {
177182
return markBoxed(inspect(Number(obj)));
178183
}
@@ -279,6 +284,17 @@ function isWeakMap(x) {
279284
return false;
280285
}
281286

287+
function isWeakRef(x) {
288+
if (!weakRefDeref || !x || typeof x !== 'object') {
289+
return false;
290+
}
291+
try {
292+
weakRefDeref.call(x);
293+
return true;
294+
} catch (e) {}
295+
return false;
296+
}
297+
282298
function isSet(x) {
283299
if (!setSize || !x || typeof x !== 'object') {
284300
return false;

test/values.js

+16
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,22 @@ test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) {
123123
t.end();
124124
});
125125

126+
test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) {
127+
var ref = new WeakRef({ a: 1 });
128+
var expectedString = 'WeakRef { ? }';
129+
t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents');
130+
131+
t.end();
132+
});
133+
134+
test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) {
135+
var registry = new FinalizationRegistry(function () {});
136+
var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}';
137+
t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys');
138+
139+
t.end();
140+
});
141+
126142
test('Strings', function (t) {
127143
var str = 'abc';
128144

0 commit comments

Comments
 (0)