diff --git a/test/mergeAndCompare.test.ts b/test/mergeAndCompare.test.ts index 5e5e6f5..154bdd3 100644 --- a/test/mergeAndCompare.test.ts +++ b/test/mergeAndCompare.test.ts @@ -1,5 +1,5 @@ import { test, expect } from 'vitest' -import { isDate, isString, isArray, isObject } from 'is-what' +import { isDate, isString, isArray } from 'is-what' import { mergeAndCompare } from '../src/index' test('conversion based on original val', () => { 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', + }, + ], + }) +})