Skip to content

Commit

Permalink
feat: add mergeArrays tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mesqueeb committed Nov 16, 2022
1 parent 49eee1c commit e7d6553
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 54 deletions.
54 changes: 0 additions & 54 deletions test/mergeAndCompare.test.ts
Expand Up @@ -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,
}
]
})
})
70 changes: 70 additions & 0 deletions 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',
},
],
})
})

0 comments on commit e7d6553

Please sign in to comment.