Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Last active May 25, 2020 22:20
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 colelawrence/e5e9b53c639ecc9555aaaa995fb9e575 to your computer and use it in GitHub Desktop.
Save colelawrence/e5e9b53c639ecc9555aaaa995fb9e575 to your computer and use it in GitHub Desktop.
Determine the difference between two iterables, returns {toAdd, toRemove}
/**
* @template T
* @param {Iterable<T>} original
* @param {Iterable<T>} updated
*/
function diffSets(original, updated) {
const toRemove = new Set(original);
const toAdd = new Set();
// compare which items are new to us
for (const id of updated) {
if (toRemove.has(id)) {
// we have it, so we shouldn't remove it
toRemove.delete(id);
} else {
toAdd.add(id);
}
}
return { toRemove, toAdd };
}
function diffSets<T>(original: Iterable<T>, updated: Iterable<T>) {
const toRemove = new Set(original);
const toAdd = new Set<T>();
// compare which items are new to us
for (const id of updated) {
if (toRemove.has(id)) {
// we have it, so we shouldn't remove it
toRemove.delete(id);
}
else {
toAdd.add(id);
}
}
return { toRemove, toAdd };
}
function diffSetsWithData<T, U>(original: Iterable<[T, U]>, updated: Iterable<[T, U]>) {
const toRemove = new Map<T, U>(original);
const toAdd = new Map<T, U>();
// compare which items are new to us
for (const [id, data] of updated) {
if (toRemove.has(id)) {
// we have it, so we shouldn't remove it
toRemove.delete(id);
} else {
toAdd.set(id, data);
}
}
return { toRemove, toAdd };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment