Last active
May 25, 2020 22:20
-
-
Save colelawrence/e5e9b53c639ecc9555aaaa995fb9e575 to your computer and use it in GitHub Desktop.
Determine the difference between two iterables, returns {toAdd, toRemove}
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
/** | |
* @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 }; | |
} |
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
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 }; | |
} |
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
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