• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Flags: --expose-gc --expose-internals
2'use strict';
3
4const common = require('../common');
5const { deepStrictEqual, strictEqual } = require('assert');
6const { IterableWeakMap } = require('internal/util/iterable_weak_map');
7
8// Ensures iterating over the map does not rely on methods which can be
9// mutated by users.
10Reflect.getPrototypeOf(function*() {}).prototype.next = common.mustNotCall();
11Reflect.getPrototypeOf(new Set()[Symbol.iterator]()).next =
12  common.mustNotCall();
13
14// It drops entry if a reference is no longer held.
15{
16  const wm = new IterableWeakMap();
17  const _cache = {
18    moduleA: {},
19    moduleB: {},
20    moduleC: {},
21  };
22  wm.set(_cache.moduleA, 'hello');
23  wm.set(_cache.moduleB, 'discard');
24  wm.set(_cache.moduleC, 'goodbye');
25  delete _cache.moduleB;
26  setImmediate(() => {
27    _cache; // eslint-disable-line no-unused-expressions
28    globalThis.gc();
29    const values = [...wm];
30    deepStrictEqual(values, ['hello', 'goodbye']);
31  });
32}
33
34// It updates an existing entry, if the same key is provided twice.
35{
36  const wm = new IterableWeakMap();
37  const _cache = {
38    moduleA: {},
39    moduleB: {},
40  };
41  wm.set(_cache.moduleA, 'hello');
42  wm.set(_cache.moduleB, 'goodbye');
43  wm.set(_cache.moduleB, 'goodnight');
44  const values = [...wm];
45  deepStrictEqual(values, ['hello', 'goodnight']);
46}
47
48// It allows entry to be deleted by key.
49{
50  const wm = new IterableWeakMap();
51  const _cache = {
52    moduleA: {},
53    moduleB: {},
54    moduleC: {},
55  };
56  wm.set(_cache.moduleA, 'hello');
57  wm.set(_cache.moduleB, 'discard');
58  wm.set(_cache.moduleC, 'goodbye');
59  wm.delete(_cache.moduleB);
60  const values = [...wm];
61  deepStrictEqual(values, ['hello', 'goodbye']);
62}
63
64// It handles delete for key that does not exist.
65{
66  const wm = new IterableWeakMap();
67  const _cache = {
68    moduleA: {},
69    moduleB: {},
70    moduleC: {},
71  };
72  wm.set(_cache.moduleA, 'hello');
73  wm.set(_cache.moduleC, 'goodbye');
74  wm.delete(_cache.moduleB);
75  const values = [...wm];
76  deepStrictEqual(values, ['hello', 'goodbye']);
77}
78
79// It allows an entry to be fetched by key.
80{
81  const wm = new IterableWeakMap();
82  const _cache = {
83    moduleA: {},
84    moduleB: {},
85    moduleC: {},
86  };
87  wm.set(_cache.moduleA, 'hello');
88  wm.set(_cache.moduleB, 'discard');
89  wm.set(_cache.moduleC, 'goodbye');
90  strictEqual(wm.get(_cache.moduleB), 'discard');
91}
92
93// It returns true for has() if key exists.
94{
95  const wm = new IterableWeakMap();
96  const _cache = {
97    moduleA: {},
98  };
99  wm.set(_cache.moduleA, 'hello');
100  strictEqual(wm.has(_cache.moduleA), true);
101}
102