Skip to content

Commit

Permalink
fix: diff now handles edge cases
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Jul 16, 2021
1 parent 1c73ba9 commit 32767b1
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
18 changes: 18 additions & 0 deletions src/diff.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,24 @@ describe("diff", () =>
}
);

it(
"Returns [ ..., [ '-', <removed> ], [ '+', <added> ], ... ] for replaced "
+"values.",
() =>
{
expect(diff([ 1 ], [ 2 ])).toEqual([ [ "-", 1 ], [ "+", 2 ] ]);
}
);

it("Does not forget additions at the end of b.", () =>
{
expect(diff([ 1 ], [ 2, 3 ])).toEqual([
[ "-", 1 ],
[ "+", 2 ],
[ "+", 3 ]
]);
});

it(
"Returns [ ..., [ '+', <added> ] ] when a is missing a value.",
() =>
Expand Down
25 changes: 19 additions & 6 deletions src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const diff = (a: any, b: any): any =>
{
if (a instanceof Array && b instanceof Array)
{

const result: any[] = [];

if (a.length === b.length)
Expand All @@ -14,6 +15,8 @@ export const diff = (a: any, b: any): any =>
return undefined;
}

let finalIndices = 0;

a.forEach((value, index) =>
{
if (b[index] === undefined)
Expand All @@ -32,21 +35,31 @@ export const diff = (a: any, b: any): any =>

else
result.push([ " ", value ]);

finalIndices++;
}

else if (value !== b[index] && value === b[index+1])
{
result.push([ "+", b[index] ], [ " ", value ]);
finalIndices += 2;
}

else if (value !== b[index] && value !== b[index+1])
{
result.push([ "-", value ], [ "+", b[index] ]);
finalIndices++;
}

else
{
result.push([ " ", value ]);
finalIndices++;
}

});

if (result.length < a.length)
{
a.slice(b.length).forEach((value) =>
result.push([ "-", value ]));
}
else if (result.length < b.length)
if (finalIndices < b.length)
{
b.slice(a.length).forEach((value) =>
result.push([ "+", value ]));
Expand Down
2 changes: 1 addition & 1 deletion src/patching.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Y from "yjs";
import { diff, } from "json-diff";
import { diff, } from "./diff";
import { arrayToYArray, objectToYMap, } from "./mapping";
import { State, StoreApi, } from "zustand/vanilla";

Expand Down

0 comments on commit 32767b1

Please sign in to comment.