Skip to content
ColonelParrot edited this page Feb 27, 2023 · 11 revisions

Import

npm:

$ npm i anabolicset
import AnabolicSet from 'anabolicset'

cdn:

<script src="https://cdn.jsdelivr.net/gh/ColonelParrot/AnabolicSet@latest/src/anabolicset.min.js"></script>

Snippets

Basic Example

const set = new AnabolicSet([1, 2, 3])
set.add(3)
set.add(4)
set.values() // [1, 2, 3, 4]

Serializer

const set = new AnabolicSet([], (obj) => obj.id)
set.addAll({ id: 1 }, { id: 2 }, { id: 2 })
set.values() // [{ id: 1 }, { id: 2 }]

Note: when adding objects, a serializer is required

union, intersect, complement...

const set1 = new AnabolicSet([1, 2, 3, 4, 5])
const set2 = new AnabolicSet([1, 2, 6])

set1.union(set2).values() // [1, 2, 3, 4, 5, 6]
set1.intersect(set2) // [1, 2]
set1.complement(set2) // [3, 4, 5]
set1.isSubsetOf(set2) // false

Methods

- constructor(values, serializer, options)

Set the initial values in set, serializer & options

const set = new AnabolicSet([1, 2, 3])
set.values() // [1, 2, 3]

const set2 = new AnabolicSet([{ id: 1 }, { id: 2 }, { id: 2 }], (obj) => obj.id)
set2.values() // [{ id: 1 }, { id: 2 }]

- addAll(...values)

Adds multiple rest parameters

set.addAll(1, 2, 3)
set.addAll(...[1, 2, 3])

- setValues(values)

Overwrite values with new values

set.setValues([4, 5, 6]) // [4, 5, 6]
set.setValues(2) // [2]

- setSerializer(serializer)

Set the new serializer function (will not reserialize values)

set.setSerializer((obj) => obj.id)
set.addAll({ id: 1 }, { id: 2 }, { id: 2 }) // [{ id: 1 }, { id: 2 }]

- union(set)

Returns AnabolicSet - gets the union of two sets

const set = new AnabolicSet([1, 2, 3])
const set2 = new AnabolicSet([3, 4, 5])
set.union(set2) // AnabolicSet [1, 2, 3, 4, 5]

- intersect(set)

Returns Array - gets the intersection of two sets

set.intersect(set2) // [3]

- complement(set)

Returns Array - gets the complement of two sets

set.complement(set2) // [1, 2]

- isSubsetOf(set)

Returns boolean - checks if current set is a subset of parameter

const set = new AnabolicSet([1, 2, 3, 4, 5])
const set2 = new AnabolicSet([4, 3, 2])
set2.isSubsetOf(set) // true

- isSupersetOf(set)

Returns boolean - checks if current set is a superset of parameter

set.isSupersetOf(set2) // true