mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 11:37:08 +00:00
Add set operations utilities
This commit is contained in:
52
lib/www/server/lib/utils/setops.js
Normal file
52
lib/www/server/lib/utils/setops.js
Normal file
@@ -0,0 +1,52 @@
|
||||
|
||||
function unique(arr) {
|
||||
const set = new Set(arr.map(JSON.stringify));
|
||||
return Array.from(set).map(JSON.parse);
|
||||
}
|
||||
|
||||
function duplicates(arr) {
|
||||
const seen = new Set();
|
||||
const dups = new Set();
|
||||
for (const item of arr.map(JSON.stringify)) {
|
||||
if (seen.has(item)) {
|
||||
dups.add(item);
|
||||
} else {
|
||||
seen.add(item);
|
||||
}
|
||||
}
|
||||
return Array.from(dups).map(JSON.parse);
|
||||
}
|
||||
|
||||
function union(arr1, arr2) {
|
||||
const set = new Set([...arr1, ...arr2].map(JSON.stringify));
|
||||
return Array.from(set).map(JSON.parse);
|
||||
}
|
||||
|
||||
|
||||
function intersection(arr1, arr2) {
|
||||
const set2 = new Set(arr2.map(JSON.stringify));
|
||||
return arr1.filter(item => set2.has(JSON.stringify(item)));
|
||||
}
|
||||
|
||||
function difference(arr1, arr2) {
|
||||
const set2 = new Set(arr2.map(JSON.stringify));
|
||||
return arr1.filter(item => !set2.has(JSON.stringify(item)));
|
||||
}
|
||||
|
||||
function symmetricDifference(arr1, arr2) {
|
||||
const set1 = new Set(arr1.map(JSON.stringify));
|
||||
const set2 = new Set(arr2.map(JSON.stringify));
|
||||
return [
|
||||
...arr1.filter(item => !set2.has(JSON.stringify(item))),
|
||||
...arr2.filter(item => !set1.has(JSON.stringify(item)))
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
unique,
|
||||
duplicates,
|
||||
union,
|
||||
intersection,
|
||||
difference,
|
||||
symmetricDifference
|
||||
}
|
||||
Reference in New Issue
Block a user