node/test/parallel/test-internal-iterable-weak-map.js
bcoe 8fa90358d7
module: refactor to use iterable-weak-map
Using an iterable WeakMap (a data-structure that uses WeakRef and
WeakMap), we are able to: stop relying on Module._cache to
serialize source maps; stop requiring an error object when calling
findSourceMap().

PR-URL: https://github.com/nodejs/node/pull/35915
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
2020-11-06 12:47:23 -08: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;
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);
}