Skip to content

Commit ee0e2f4

Browse files
committed
Set operations example
1 parent fe48132 commit ee0e2f4

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

JavaScript/2-distinct.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
function distinct(dataset) {
3+
const distinct = (dataset) => {
44
const keys = new Set();
55
return dataset.filter(record => {
66
const cols = Object.keys(record).sort();
@@ -9,9 +9,11 @@ function distinct(dataset) {
99
keys.add(key);
1010
return !has;
1111
});
12-
}
12+
};
1313

14-
let flights = [
14+
// Usage
15+
16+
const flights = [
1517
{ from: 'Kiev', to: 'Rome' },
1618
{ from: 'Kiev', to: 'Warsaw' },
1719
{ from: 'Dublin', to: 'Riga' },
@@ -22,6 +24,6 @@ let flights = [
2224

2325
console.dir({ flights });
2426

25-
flights = distinct(flights);
27+
const directions = distinct(flights);
2628

27-
console.dir({ flights });
29+
console.dir({ directions });

JavaScript/3-operations.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
const union = (s1, s2) => new Set([...s1, ...s2]);
4+
5+
const intersection = (s1, s2) => new Set(
6+
[...s1].filter(v => s2.has(v))
7+
);
8+
9+
const difference = (s1, s2) => new Set(
10+
[...s1].filter(v => !s2.has(v))
11+
);
12+
13+
const complement = (s1, s2) => difference(s2, s1);
14+
15+
// Usage
16+
17+
const cities1 = new Set(['Beijing', 'Kiev']);
18+
const cities2 = new Set(['Kiev', 'London', 'Baghdad']);
19+
20+
const operations = [union, intersection, difference, complement];
21+
22+
const results = operations.map(operation => ({
23+
[operation.name]: operation(cities1, cities2)
24+
}));
25+
26+
console.dir({ cities1, cities2 });
27+
console.dir(results);

0 commit comments

Comments
 (0)