node/test/parallel/test-internal-iterable-weak-map.js
Michaël Zasso bf31d3c3b1
tools: enable no-unused-expressions lint rule
Fixes: https://github.com/nodejs/node/issues/36246

PR-URL: https://github.com/nodejs/node/pull/36248
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2020-12-07 20:33:45 +01:00

96 lines
2.2 KiB
JavaScript

// Flags: --expose-gc --expose-internals
'use strict';
require('../common');
const { deepStrictEqual, strictEqual } = require('assert');
const { IterableWeakMap } = require('internal/util/iterable_weak_map');
// It drops entry if a reference is no longer held.
{
const wm = new IterableWeakMap();
const _cache = {
moduleA: {},
moduleB: {},
moduleC: {},
};
wm.set(_cache.moduleA, 'hello');
wm.set(_cache.moduleB, 'discard');
wm.set(_cache.moduleC, 'goodbye');
delete _cache.moduleB;
setImmediate(() => {
_cache; // eslint-disable-line no-unused-expressions
globalThis.gc();
const values = [...wm];
deepStrictEqual(values, ['hello', 'goodbye']);
});
}
// It updates an existing entry, if the same key is provided twice.
{
const wm = new IterableWeakMap();
const _cache = {
moduleA: {},
moduleB: {},
};
wm.set(_cache.moduleA, 'hello');
wm.set(_cache.moduleB, 'goodbye');
wm.set(_cache.moduleB, 'goodnight');
const values = [...wm];
deepStrictEqual(values, ['hello', 'goodnight']);
}
// It allows entry to be deleted by key.
{
const wm = new IterableWeakMap();
const _cache = {
moduleA: {},
moduleB: {},
moduleC: {},
};
wm.set(_cache.moduleA, 'hello');
wm.set(_cache.moduleB, 'discard');
wm.set(_cache.moduleC, 'goodbye');
wm.delete(_cache.moduleB);
const values = [...wm];
deepStrictEqual(values, ['hello', 'goodbye']);
}
// It handles delete for key that does not exist.
{
const wm = new IterableWeakMap();
const _cache = {
moduleA: {},
moduleB: {},
moduleC: {},
};
wm.set(_cache.moduleA, 'hello');
wm.set(_cache.moduleC, 'goodbye');
wm.delete(_cache.moduleB);
const values = [...wm];
deepStrictEqual(values, ['hello', 'goodbye']);
}
// It allows an entry to be fetched by key.
{
const wm = new IterableWeakMap();
const _cache = {
moduleA: {},
moduleB: {},
moduleC: {},
};
wm.set(_cache.moduleA, 'hello');
wm.set(_cache.moduleB, 'discard');
wm.set(_cache.moduleC, 'goodbye');
strictEqual(wm.get(_cache.moduleB), 'discard');
}
// It returns true for has() if key exists.
{
const wm = new IterableWeakMap();
const _cache = {
moduleA: {},
};
wm.set(_cache.moduleA, 'hello');
strictEqual(wm.has(_cache.moduleA), true);
}