Skip to content

Set

Module Collections.Sets

A set stores unique items - only things that are different from each other. But what constitutes ‘different’?

The default Javascript Set compares basic data types by value (eg. numbers, strings):

let a = 43;
let b = 43;
a === b; // True
a = `hello`;
b = `hello`;
a === b; // True

But if you have objects, they are compared by reference rather than value.

let a = { value: 43 };
let b = { value: 43 };
a === b; // False

Especially when working with immutable data, this logic isn’t helpful. Instead, we’d rather say objects are identical if they have the same properties and values - even if they are two separate instances.

Ixfx’s Set implementation allows for value-based comparisons.

Sets.immutable creates an immutable set of Interface Sets.ISetImmutable

import { Sets } from "https://unpkg.com/@ixfx/collections/bundle"
// Data to add
const people = [
{name: `Barry`, city: `London`},
{name: `Sally`, city: `Bristol`}
];
// Create a set, defining how keys will be generated
let s = Sets.mutable(person => {
// Key person objects by name and city.
// ie. Generated keys will be: `Barry-London`, `Sally-Bristol`
return `${person.name}-${person.city}`
});
// Add list - since it's immutable, a changed copy is returned
s = s.add(...people);
// Accessing: has/get
s.has({name:`Barry`, city:`Manchester`})); // False, key is different (Barry-Manchester)
s.has({name:`Barry`, city:`London`})); // True, we have Barry-London as a key
s.has(people[1]); // True, key of object is found (Sally-Bristol)
// Deleting (returns changed copy)
s = s.delete({name:`Barry`, city:`London`});

Sets.mutable creates a set of Interface Sets.ISetMutable . The mutable set has events to monitor changes to data.

import { Sets } from "https://unpkg.com/@ixfx/collections/bundle"
// Data to add
const people = [
{name: `Barry`, city: `London`},
{name: `Sally`, city: `Bristol`}
];
// Create a set, defining how keys will be generated
const set = Sets.mutable(person => {
// Key person objects by name and city.
// ie. Generated keys will be: `Barry-London`, `Sally-Bristol`
return `${person.name}-${person.city}`
});
// Add list
set.add(...people);
// Demo:
set.has({name:`Barry`, city:`Manchester`})); // False, key is different (Barry-Manchester)
set.has({name:`Barry`, city:`London`})); // True, we have Barry-London as a key
set.has(people[1]); // True, key of object is found (Sally-Bristol)
// Sub module
import { Sets } from "@ixfx/collections.js"
// Eg: Sets.immutable();
// Whole module
import * as Collections from "@ixfx/collections.js"
// Eg: Collections.Sets.immutable();
// From bundle
import { Collections } from "@ixfx"
// Eg: Collections.Sets.immutable();
// And within your HTML's <HEAD> </HEAD> block:
<script type="importmap">{ "imports": { "@ixfx":"/ixfx/index.js", "@ixfx/": "/ixfx/" } }</script>