Skip to content

Commit

Permalink
补充单测用例
Browse files Browse the repository at this point in the history
  • Loading branch information
ximing committed Jan 25, 2024
1 parent c2540ab commit a24249c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
28 changes: 28 additions & 0 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,33 @@ describe('diff', () => {
'c.e.f': 'hello world',
i: ['a', 'b']
});

expect(diff({ a: {} }, { a: null })).toStrictEqual({ a: {} });
});
test('null', () => {
expect(diff({}, null, 'test')).toStrictEqual({ test: {} });
expect(diff(null, {}, 'test')).toStrictEqual({ test: null });
});
test('array', () => {
expect(diff({ a: [1, 2] }, { a: {} })).toStrictEqual({ a: [1, 2] });
expect(diff({ a: [[1, 2], 3] }, { a: [{}, 3] })).toStrictEqual({ 'a[0]': [1, 2] });
expect(diff({ a: [[1, 2], 3] }, { a: [[0, 1, 2], 3] })).toStrictEqual({ 'a[0]': [1, 2] });
expect(diff({ a: [[1, 2], 3] }, { a: [[2, 3], 3] })).toStrictEqual({
'a[0][0]': 1,
'a[0][1]': 2
});
expect(diff({ a: [{ a: 1 }, 3] }, { a: [{ a: 2 }, 3] })).toStrictEqual({ 'a[0].a': 1 });
expect(diff({ a: [[null, 2], 3] }, { a: [[{ a: 2 }], 3] })).toStrictEqual({
'a[0][0]': null,
'a[0][1]': 2
});
expect(
diff({ a: [[{ a: 3, b: undefined }], 3] }, { a: [[{ a: 2, b: 3 }], 3] })
).toStrictEqual({
'a[0][0]': {
a: 3,
b: undefined
}
});
});
});
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@ const diffArrToPath = (to: any[], from: any[], res: any = {}, keyPrev = '') => {
};

const diffObjToPath = (to: any, from: any, res: any = {}, keyPrev = '') => {
const keys = keyList(to);
const len = keys.length;
if (to == null) {
res[keyPrev] = null;
return res;
Expand All @@ -72,6 +70,8 @@ const diffObjToPath = (to: any, from: any, res: any = {}, keyPrev = '') => {
res[keyPrev] = to;
return res;
}
const keys = keyList(to);
const len = keys.length;
for (let i = 0; i < len; i++) {
const key = keys[i];
const toItem = to[key];
Expand Down Expand Up @@ -124,7 +124,7 @@ const diffObjToPath = (to: any, from: any, res: any = {}, keyPrev = '') => {
return res;
};

export const diff = function(newData: any, oldData: any,keyPrev = '') {
export const diff = function(newData: any, oldData: any, keyPrev = '') {
const target = {};
diffObjToPath(newData, oldData, target, keyPrev);
return target;
Expand Down

0 comments on commit a24249c

Please sign in to comment.