mirror of
https://codeberg.org/yeentown/barkey.git
synced 2025-07-07 12:36:57 +00:00
minor optimization to diff-arrays
This commit is contained in:
parent
6b3ddc6768
commit
8a2ed3bc86
2 changed files with 7 additions and 5 deletions
|
@ -10,8 +10,9 @@ export interface DiffResult<T> {
|
|||
|
||||
/**
|
||||
* Calculates the difference between two snapshots of data.
|
||||
* Null, undefined, and empty arrays are supported, and values do not have to be unique.
|
||||
* Null, undefined, and empty arrays are supported, and duplicate values are ignored.
|
||||
* Result sets are de-duplicated, and will be empty if no data was added or removed (respectively).
|
||||
* The inputs are treated as un-ordered, so a re-ordering of the same data will NOT be considered a change.
|
||||
* @param dataBefore Array containing data before the change
|
||||
* @param dataAfter Array containing data after the change
|
||||
*/
|
||||
|
@ -26,7 +27,8 @@ export function diffArrays<T>(dataBefore: T[] | null | undefined, dataAfter: T[]
|
|||
|
||||
for (const host of before) {
|
||||
// before and NOT after => removed
|
||||
if (!after.has(host)) {
|
||||
// delete operation removes duplicates to speed up the "after" loop
|
||||
if (!after.delete(host)) {
|
||||
removed.push(host);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -18,19 +18,19 @@ describe(diffArrays, () => {
|
|||
expect(result.removed).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should remove before when added is empty', () => {
|
||||
it('should remove before when after is empty', () => {
|
||||
const result = diffArrays([1, 2, 3], []);
|
||||
expect(result.added).toHaveLength(0);
|
||||
expect(result.removed).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('should deduplicate before when added is empty', () => {
|
||||
it('should deduplicate before when after is empty', () => {
|
||||
const result = diffArrays([1, 1, 2, 2, 3], []);
|
||||
expect(result.added).toHaveLength(0);
|
||||
expect(result.removed).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('should remove after when before is empty', () => {
|
||||
it('should add after when before is empty', () => {
|
||||
const result = diffArrays([], [1, 2, 3]);
|
||||
expect(result.added).toEqual([1, 2, 3]);
|
||||
expect(result.removed).toHaveLength(0);
|
||||
|
|
Loading…
Add table
Reference in a new issue