Skip to content

Instantly share code, notes, and snippets.

@danclien
Created September 25, 2018 23:43
Show Gist options
  • Save danclien/827dca3fc7ba87620f07eefaac717dff to your computer and use it in GitHub Desktop.
Save danclien/827dca3fc7ba87620f07eefaac717dff to your computer and use it in GitHub Desktop.

Random thoughts on sets

Sets can be generalized as a function that takes an argument and returns true or false.

Sets of numbers

For a specific set of numbers, you can write it as:

const mySetOfNumbers = num => [1,2,3,4,5].includes(num);

To check if a number is in the set, you can just call it with the number:

mySetOfNumbers(1); // true
mySetOfNumbers(9); // false

Unions and intersections

If you had two sets, you can get the union or intersections like any normal set.

Given:

const set1 = num => [1,2,3,4,5].includes(num);
const set2 = num => [2,4,6,8,10].includes(num);

Union

Remember:

  • The union of two sets is still a set
  • A set is generalized as a function that takes an argument and returns true or false

Since the union is a set, we can start writing out a blank function for the result:

const set1UnionSet2 = num => {
  // return true or false here
}

What could we fill in below to get the union of set1 and set2?

Answer:

const set1UnionSet2 = num => set1(num) || set2(num);
set1UnionSet2(0);  // false
set1UnionSet2(1);  // true
set1UnionSet2(5);  // true
set1UnionSet2(10); // true

Intersection

The same can be down for the intersection of two sets:

const set1IntersectSet2 = num => set1(num) && set2(num);
set1IntersectSet2(0) // false
set1IntersectSet2(1) // false
set1IntersectSet2(4) // true

Going more abstract

So, we don't actually need to include all numbers inside the function anywhere.

The set of even and odd numbers in JavaScript would be:

const evenNumbers = num => num % 2 == 0;
const oddNumbers = num => num % 2 == 1;
evenNumbers(5);       // false
oddNumbers(7);        // true
evenNumbers(1235236); // true

The set of numbers greater than 10 would be:

const greaterThan10 = num => num > 10;
greaterThan10(0)       // false
greaterThan10(100000)  // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment