Skip to content

Commit

Permalink
Fix deep merge when previously empty
Browse files Browse the repository at this point in the history
  • Loading branch information
Swizz committed Aug 26, 2019
1 parent ccd9ccd commit 4e909fa
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/index.js
Expand Up @@ -8,7 +8,7 @@ export function diff(from, to, deep) {
for (var key in to) {
if (key in done || from[key] === to[key]) continue

if (deep && (typeof from[key] === "object" || typeof to[key] === "object")) {
if (deep && (typeof from[key] === "object" && typeof to[key] === "object")) {
var deep_patch = diff(from[key], to[key], deep)

if (Object.keys(deep_patch.do).length) {
Expand Down Expand Up @@ -59,4 +59,4 @@ export function patch(from, diff, deep, array, clean) {
}
}
return array && "length" in to ? Array.from(to) : to
}
}
122 changes: 122 additions & 0 deletions tests/diff.test.js
Expand Up @@ -345,3 +345,125 @@ describe("array", () => {
expect(Array.from({ ...to, ...patch.undo })).toEqual(from)
})
})

describe("empty", () => {
test("empty from", () => {
const from = {}

const to = { a: 1 }

const patch = diff(from, to)

expect(patch.do).toEqual(to)

expect(patch.undo).toEqual({
a: undefined
})

expect({ ...from, ...patch.do }).toEqual(to)

expect({ ...to, ...patch.undo }).toEqual(from)
})

test("empty to", () => {
const from = { a: 1 }

const to = {}

const patch = diff(from, to)

expect(patch.do).toEqual({
a: undefined
})

expect(patch.undo).toEqual(from)

expect({ ...from, ...patch.do }).toEqual(to)

expect({ ...to, ...patch.undo }).toEqual(from)
})
})

describe("empty array", () => {
test("empty from", () => {
const from = []

const to = [1]

const patch = diff(from, to)

expect(patch.do).toEqual({
0: 1,
length: 1
})

expect(patch.undo).toEqual({
0: undefined,
length: 0
})

expect(Array.from({ ...from, ...patch.do })).toEqual(to)

expect(Array.from({ ...to, ...patch.undo })).toEqual(from)
})

test("empty to", () => {
const from = [1]

const to = []

const patch = diff(from, to)

expect(patch.do).toEqual({
0: undefined,
length: 0
})

expect(patch.undo).toEqual({
0: 1,
length: 1
})

expect(Array.from({ ...from, ...patch.do })).toEqual(to)

expect(Array.from({ ...to, ...patch.undo })).toEqual(from)
})
})

describe("deep empty", () => {
test("deep empty object", () => {
const from = {}

const to = { a: { b: 1 } }

const patch = diff(from, to, true)

expect(patch.do).toEqual(to)

expect(patch.undo).toEqual({
a: undefined
})

expect({ ...from, ...patch.do }).toEqual(to)

expect({ ...to, ...patch.undo }).toEqual(from)
})

test("deep empty array", () => {
const from = {}

const to = { a: [1] }

const patch = diff(from, to, true)

expect(patch.do).toEqual(to)

expect(patch.undo).toEqual({
a: undefined
})

expect({ ...from, ...patch.do }).toEqual(to)

expect({ ...to, ...patch.undo }).toEqual(from)
})
})

0 comments on commit 4e909fa

Please sign in to comment.