Last active
August 2, 2021 20:42
-
-
Save gioragutt/49110069e12680b0de0c818a666adb90 to your computer and use it in GitHub Desktop.
Example for facebook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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