From ac078e445bbedce23c4039daef5498dba6df9bb7 Mon Sep 17 00:00:00 2001 From: Jos de Jong Date: Wed, 16 Sep 2020 13:33:56 +0200 Subject: [PATCH] Create empty array on inserted structure containing an array --- src/logic/operations.js | 16 ++++++++------ src/logic/operations.test.js | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 src/logic/operations.test.js diff --git a/src/logic/operations.js b/src/logic/operations.js index e4ec7a8..6d81f58 100644 --- a/src/logic/operations.js +++ b/src/logic/operations.js @@ -5,7 +5,7 @@ import { getParentPath } from '../logic/selection.js' import { getIn } from '../utils/immutabilityHelpers.js' import { compileJSONPointer } from '../utils/jsonPointer.js' import { findUniqueName } from '../utils/stringUtils.js' -import { isObjectOrArray } from '../utils/typeUtils.js' +import { isObject } from '../utils/typeUtils.js' /** * Create a JSONPatch for an insert operation. @@ -270,16 +270,18 @@ export function createNewValue (doc, selection, type) { case 'array': return [] - case 'structure': + case 'structure': { const parentPath = getParentPath(selection) const parent = getIn(doc, parentPath) if (Array.isArray(parent) && !isEmpty(parent)) { const jsonExample = first(parent) const structure = cloneDeepWith(jsonExample, (value) => { - return isObjectOrArray(value) - ? undefined // leave as is - : '' + return Array.isArray(value) + ? [] + : isObject(value) + ? undefined // leave object as is, will recurse into it + : '' }) console.log('structure', jsonExample, structure) @@ -289,8 +291,10 @@ export function createNewValue (doc, selection, type) { // no example structure return '' } + } - default: '' + default: + return '' } } diff --git a/src/logic/operations.test.js b/src/logic/operations.test.js new file mode 100644 index 0000000..698cd37 --- /dev/null +++ b/src/logic/operations.test.js @@ -0,0 +1,42 @@ +import assert from 'assert' +import { createNewValue } from './operations.js' + +describe('operations', () => { + describe('createNewValue', () => { + it('should create a value of type "value"', () => { + assert.strictEqual(createNewValue({}, null, 'value'), '') + }) + + it('should create a value of type "object"', () => { + assert.deepStrictEqual(createNewValue({}, null, 'object'), {}) + }) + + it('should create a value of type "array"', () => { + assert.deepStrictEqual(createNewValue({}, null, 'array'), []) + }) + + it('should create a simple value via type "structure"', () => { + assert.deepStrictEqual(createNewValue([1, 2, 3], { paths: [[0]] }, 'structure'), '') + }) + + it('should create a nested object via type "structure"', () => { + const doc = [ + { + a: 2, + b: { + c: 3 + }, + d: [1, 2, 3] + } + ] + + assert.deepStrictEqual(createNewValue(doc, { paths: [[0]] }, 'structure'), { + a: '', + b: { + c: '' + }, + d: [] + }) + }) + }) +})