Skip to content

Instantly share code, notes, and snippets.

@jdrew1303
Created July 11, 2018 22:47
Show Gist options
  • Save jdrew1303/0818bf33c98587d3a40be739c8daa9d9 to your computer and use it in GitHub Desktop.
Save jdrew1303/0818bf33c98587d3a40be739c8daa9d9 to your computer and use it in GitHub Desktop.
Sets
import * as R from 'ramda';
// union and difference are more or less the same except
// for the operation performed
const abstractSummation = R.curry((operation, a, b) => R.reduce((s, e) => {
s[operation](e);
return s;
}, new Set(a), b));
// for the given sets:
// A={2,4,6,8,10}
// B={1,2,3,4,5}
// then Union: A∪B = {1,2,3,4,5,6,8,10}
// https://upload.wikimedia.org/wikipedia/commons/3/30/Venn0111.svg
export const union = abstractSummation('add');
// for the given sets:
// A={2,4,6,8,10}
// B={1,2,3,4,5}
// then Difference: A-B = {6,8,10}
// https://upload.wikimedia.org/wikipedia/commons/4/46/Venn0110.svg
export const difference = abstractSummation('delete');
// for the given sets:
// A={2,4,6,8,10}
// B={1,2,3,4,5}
// then Complement: A^B = {1,3,5}
// https://upload.wikimedia.org/wikipedia/commons/e/eb/Venn1010.svg
export const complement = R.curry((a, b) => difference(b, a));
// for the given sets:
// A={2,4,6,8,10}
// B={1,2,3,4,5}
// then Intersection: A∩B = {2,4}
// In this we use De Morgan's Law and some basic juggling to
// remove the need to write a seperate function.
// https://upload.wikimedia.org/wikipedia/commons/9/99/Venn0001.svg
export const intersection = R.curry((a, b) => difference(a, difference(a, b)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment