Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Created August 18, 2021 15:24
Show Gist options
  • Save damiancipolat/4b039cdedfc3cb04e06f2c8262b4a30f to your computer and use it in GitHub Desktop.
Save damiancipolat/4b039cdedfc3cb04e06f2c8262b4a30f to your computer and use it in GitHub Desktop.
Javascript special array set operations
/*
Return the sets intersection.
Params
arrA : array
arrB : array
Return
array
*/
const intersection = (arrA,arrB) => arrA.filter(x => arrB.includes(x));
/*
Return the difference of two sets.
Params
arrA : array
arrB : array
Return
array
*/
const difference = (arrA,arrB) => arrA.filter(x => !arrB.includes(x));
/*
Make the simetric difference between two arrays.
Params
arrA : array
arrB : array
Return
array
*/
const symDifference = (arrA,arrB) => arrA.filter(x => !arrB.includes(x)).concat(arrB.filter(x => !arrA.includes(x)));
/*
Return the union between two sets.
Params
arrA : array
arrB : array
Return
array
*/
const union = (arrA,arrB) => [...arrA, ...arrB];
/*
Return the union of two sets handling repetead elements.
Params
topic:string,
msg: {structure}
Return
promise
*/
const unionUnique = (arrA,arrB)=> [...new Set([...arrA, ...arrB])];
module.exports = {
intersection,
difference,
symDifference,
union,
unionUnique
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment