Sets can be generalized as a function that takes an argument and returns
true
or false
.
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
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);
Remember:
- The union of two sets is still a set
- A set is generalized as a function that takes an argument and returns
true
orfalse
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
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
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