From 19045e98bf8216858fe4bdd598f84414664aeb10 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 19 Feb 2025 14:42:20 +0800 Subject: [PATCH] subarray same value handle --- jsonpatch.go | 4 +++- jsonpatch_subarray_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 jsonpatch_subarray_test.go diff --git a/jsonpatch.go b/jsonpatch.go index 9197f61..47480da 100644 --- a/jsonpatch.go +++ b/jsonpatch.go @@ -408,7 +408,9 @@ func compareArray(av, bv []interface{}, p string) []Operation { break } } - if !found { + + newElementButEqualToAnExistingOne := found && i >= len(av) + if !found || newElementButEqualToAnExistingOne { retval = append([]Operation{NewPatch("add", makePath(p, i), v)}, retval...) } } diff --git a/jsonpatch_subarray_test.go b/jsonpatch_subarray_test.go new file mode 100644 index 0000000..f4ca546 --- /dev/null +++ b/jsonpatch_subarray_test.go @@ -0,0 +1,25 @@ +package jsonpatch + +import ( + "log" + "testing" + + "github.com/stretchr/testify/assert" +) + +var subArray1_current = `{"created":1739943104628936621,"updated":0,"index":"test","path":"test","data":{"subFields":[{"one":"one","two":"two","three":3}]}}` +var subArray1_target = `{"created":1739943104628936621,"updated":1739942662496282458,"index":"test","path":"test","data":{"subFields":[{"one":"one","two":"two","three":3},{"one":"one","two":"two","three":3}]}}` + +var subArray2_current = `{"created":1739943104628936621,"updated":1739942662496282458,"index":"test","path":"test","data":{"subFields":[{"one":"one","two":"two","three":3},{"one":"one","two":"two","three":3}]}}` +var subArray2_target = `{"created":1739943104628936621,"updated":1739942662496282459,"index":"test","path":"test","data":{"subFields":[{"one":"one","two":"two","three":3},{"one":"one","two":"two","three":3},{"one":"one","two":"two","three":3}]}}` + +func TestSubfieldArray(t *testing.T) { + patch, e := CreatePatch([]byte(subArray1_current), []byte(subArray1_target)) + assert.NoError(t, e) + assert.Equal(t, len(patch), 2, "the patch should update 2 fields") + + patch, e = CreatePatch([]byte(subArray2_current), []byte(subArray2_target)) + assert.NoError(t, e) + log.Println("OP", patch) + assert.Equal(t, len(patch), 2, "the patch should update 2 fields") +}