diff --git a/test/mergeAndCompare.test.ts b/test/mergeAndCompare.test.ts index e5e47e0..154bdd3 100644 --- a/test/mergeAndCompare.test.ts +++ b/test/mergeAndCompare.test.ts @@ -60,57 +60,3 @@ test('Extend with custom concat arrays', () => { // const res2 = mergeAndCompare(concatArr, ['a'], ['b']) // expect(res2).toEqual( ['a', 'b']) }) - -test('undefined object', () => { - const origin = { - pages: { - 'aa': 'ttt', - }, - } - - const newData = { - pages: { - 'aa': '1111', - 'bb': '2222', - } - } - - function convertTimestamps(originVal: any, targetVal: any, key: any) { - if (originVal !== undefined) - return targetVal - } - - const res = mergeAndCompare(convertTimestamps, origin, newData) - expect(res as any).toEqual({ pages: { aa: "1111", bb: undefined } }) -}) - -test('undefined array', () => { - function convertTimestamps(originVal: any, targetVal: any, key: any) { - if (originVal !== undefined) - return targetVal - } - const origin = { - date: [ - { - 'new': 'aaa', - } - ] - } - const target = { - date: [ - { - 'new': 'aaa', - 'old': 'bbb', - } - ] - } - const res = mergeAndCompare(convertTimestamps, origin, target) - expect(res as any).toEqual({ - date: [ - { - 'new': 'aaa', - 'old': undefined, - } - ] - }) -}) \ No newline at end of file diff --git a/test/mergeArrays.test.ts b/test/mergeArrays.test.ts new file mode 100644 index 0000000..2ed3cc9 --- /dev/null +++ b/test/mergeArrays.test.ts @@ -0,0 +1,70 @@ +import { test, expect } from 'vitest' +import { isArray } from 'is-what' +import { mergeAndCompare, merge } from '../src/index' + +function mergeArrays(originVal: any, newVal: any): any | any[] { + if (isArray(originVal) && isArray(newVal)) { + // concat & merge logic + const overlappingPart = originVal.slice(0, newVal.length) + + return overlappingPart + .map((p, i) => (newVal[i] ? merge(p, newVal[i]) : p)) + .concat( + newVal.length > originVal.length + ? originVal.slice(newVal.length) + : newVal.slice(originVal.length) + ) + } + return newVal // always return newVal as fallback!! +} + +test('undefined object', () => { + function merge(originVal: any, targetVal: any, key: any) { + if (originVal !== undefined) return targetVal + } + + const origin = { + pages: { + aa: 'ttt', + }, + } + + const newData = { + pages: { + aa: '1111', + bb: '2222', + }, + } + + const res = mergeAndCompare(mergeArrays, origin, newData) + expect(res as any).toEqual({ pages: { aa: '1111', bb: '2222' } }) +}) + +test('undefined array', () => { + const origin = { + date: [ + { + new: 'aa', + something: 'yy', + }, + ], + } + const target = { + date: [ + { + new: 'bb', + old: 'zz', + }, + ], + } + const res = mergeAndCompare(mergeArrays, origin, target) + expect(res as any).toEqual({ + date: [ + { + new: 'bb', + something: 'yy', + old: 'zz', + }, + ], + }) +})