Skip to content

Set

Module Collections.Sets

A set stores unique items. But what constitutes ‘unique’? The default Javascript Set compares basic data types by value (eg numbers, strings), but objects by reference. The ixfx set favours comparing by value also for objects. This is particularly important when we work with immutable data.

Immutable

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

import { Sets } from "https://unpkg.com/ixfx/dist/collections.js"
// 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`});

Mutable

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

// 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)