Skip to content

Instantly share code, notes, and snippets.

@b0o
Created August 6, 2021 02:36
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 b0o/722be3414c4dec5f2aa4b1b9512481b1 to your computer and use it in GitHub Desktop.
Save b0o/722be3414c4dec5f2aa4b1b9512481b1 to your computer and use it in GitHub Desktop.
Operations over sets
const union = (...sets) => new Set(sets.flatMap(s => [...s]))
const intersection = (a, b, ...rest) => (rest.length ? intersection : (s => new Set(s)))([...a].reduce((acc, e) => b.has(e) ? [...acc, e] : acc, []), ...rest)
const difference = (...sets) => [...intersection(...sets)].reduce((acc, e) => !acc.delete(e) || acc, union(...sets))
const leftDifference = (left, ...rights) => difference(left, intersection(left, union(...rights)))
const rightDifference = (...sets) => leftDifference(...sets.reverse())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment