Skip to content

Instantly share code, notes, and snippets.

@gioragutt
Last active August 2, 2021 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gioragutt/49110069e12680b0de0c818a666adb90 to your computer and use it in GitHub Desktop.
Save gioragutt/49110069e12680b0de0c818a666adb90 to your computer and use it in GitHub Desktop.
Example for facebook
const smallArray: string[] = []; // initial value IDK?
// unless you need to update the array itself, you can leave with the set.
// If you need to update the array, you can do that close to actions on the set.
const smallSet = new Set<string>(smallArray);
addEventListener('new-array-to-compare', (bigArray: string[]) => {
for (const value of bigArray) {
if (smallSet.delete(value)) {
// value was in smallSet and was deleted
// here you can remove the item from smallArray if you need.
// However, as you can see, each deletion would cause an O(n) iteration on the array,
// so if you can live with the small array being just a Set and not an array, I'd do that.
}
}
});
addEventListener('new-item-for-small-array', (newItem: string) => {
smallSet.add(newItem);
// or
if (!smallSet.has(newItem)) {
smallSet.add(newItem);
smallArray.push(newItem); // if you need to update the array as well for some reason
}
});
const smallArray = [];
addEventListener('new-array-to-compare', (bigArray: string[]) => {
const bigSet = new Set<string>(bigArray);
// not the prettiest, but iterating over an array and modifying it on the way is pretty ugly.
// going from the end to the beginning makes it so that the indices will stay valid and you
// won't have to alter them manually if you end up deleting an index.
for (let i = smallArray.length - 1; i >= 0; i--) {
if (bigSet.has(smallArray[i]) {
smallArray.splice(i, 1)
}
}
});
addEventListener('new-item-for-small-array', (newItem: string) => {
smallArray.push(newItem);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment