summaryrefslogtreecommitdiff
path: root/test/parallel/test-internal-iterable-weak-map.js
blob: e0282c9081ee33bc473314018093c06139ec97f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 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);
}