February 23, 2023
TestsSource
- Fundamentals
- set.add(1) is the same as set.add("1")??
- What happens when we add 0 and -0?
- Garbage collection for Weak* ...
Source Code
The source code we wrote during the event.
map-set-weakmap.spec.js
import {strict as assert} from 'assert';
describe('Fundamentals', () => {
it('creating a set using `new Set()` creates an empty set', () => {
const set = new Set();
assert.equal(set.size, 0);
});
it('add one item, using `add` and the size is 1', () => {
const set = new Set();
set.add({not: 'primitive'});
assert.equal(set.size, 1);
});
it('after adding a primitive item, it`s in the Set', () => {
const set = new Set();
set.add(1);
assert.equal(set.has(1), true);
});
it('after adding an object, we find it in the Set', () => {
const set = new Set();
const thisObject = {an: 'object'};
set.add(thisObject);
assert.equal(set.has(thisObject), true);
});
});
describe('set.add(1) is the same as set.add("1")??', () => {
it('adding a number 1 and a string "1" makes a Set of size 2', () => {
const set = new Set();
set.add(1);
set.add('1');
assert.equal(set.size, 2);
});
it('adding 1 twice creates a Set of size 1', () => {
const set = new Set();
set.add(1);
set.add(1);
assert.equal(set.size, 1);
});
it('adding "1" twice creates a Set of size 1', () => {
const set = new Set();
set.add("1");
set.add("1");
assert.equal(set.size, 1);
});
it('adding a look-alike object twice results of size 2', () => {
const set = new Set();
set.add(() => {});
set.add(() => {});
assert.equal(set.size, 2);
});
});
describe('What happens when we add 0 and -0?', () => {
it('adding -0 to a Set, then 0 is in the Set', () => {
const set = new Set();
set.add(-0);
assert.equal(set.has(0), true);
});
it('-0 not equals exactly 0, using Object.is()', () => {
assert.equal(Object.is(-0, 0), false);
});
it('we add -0, when iterating over the set we get 0', () => {
// see https://tc39.es/ecma262/#sec-set.prototype.add point 4
const set = new Set();
set.add(-0);
for (const value of set) {
assert(Object.is(value, 0));
}
});
});
import 'expose-gc';
describe('Garbage collection for Weak* ...', () => {
xit('a WeakMap does not hold on to its entries when gc runs', () => {
const weakmap = new WeakMap();
const key = new WeakRef({});
weakmap.set(key.deref(), 42);
// collect all your trash
global.gc(); // requires `import 'expose-gc';`
assert.equal(key.deref(), null);
});
xit('deleting the prop of an obj, which was used in the WeakMap, it wont be in the WeakMap', () => {
const obj = {x: 1};
const weakmap = new WeakMap();
weakmap.set(obj.x, 42);
delete obj.x;
assert.equal(weakmap.has(1), false);
});
});