Skip to content

Instantly share code, notes, and snippets.

@sam-w
Created November 24, 2020 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam-w/22f5ea77d9cca1f142b1d052d92e4378 to your computer and use it in GitHub Desktop.
Save sam-w/22f5ea77d9cca1f142b1d052d92e4378 to your computer and use it in GitHub Desktop.
Set Operations
/**
* Returns the union of the two sets (`a ∪ b`),
* i.e. all elements present in either set.
*/
export const union = <T>(a: Set<T>, b: Set<T>) => new Set(
[...a].concat(...b)
)
/**
* Returns the intersection of the two sets (`a ∩ b`),
* i.e. only the elements contained in both sets.
*/
export const intersection = <T>(a: Set<T>, b: Set<T>) => new Set(
[...a].filter((x) => b.has(x))
)
/**
* Returns the difference between the two sets (`a - b`),
* i.e. the elements contained in `a` but not in `b`.
*/
export const difference = <T>(a: Set<T>, b: Set<T>) => new Set(
[...a].filter((x) => !b.has(x))
)
/**
* Returns the symmetric difference between the two sets (`a Δ b`),
* i.e. the elements contained in `a` but not in `b` and the elements
* contained in `b` but not in `a`.
*/
export const symmetricDifference = <T>(a: Set<T>, b: Set<T>) => new Set(
[...difference(a, b)].concat([...difference(b, a)])
)
/**
* Returns `true` if `a` is a superset of `b` - `a ⊇ b`
* i.e. if all values in `b` are also contained in `a`.
*/
export const isSuperset = <T>(a: Set<T>, b: Set<T>) =>
[...b].every((x) => a.has(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment