提交 9d34bc55 编写于 作者: S Sandeep Somavarapu

#22799 Enhance json edit to support removing elements from array

上级 a92ddb56
......@@ -81,6 +81,7 @@ export function setProperty(text: string, path: JSONPath, value: any, formatting
} else if (parent.type === 'array' && typeof lastSegment === 'number') {
let insertIndex = lastSegment;
if (insertIndex === -1) {
// Insert
let newProperty = `${JSON.stringify(value)}`;
let edit: Edit;
if (parent.children.length === 0) {
......@@ -91,7 +92,26 @@ export function setProperty(text: string, path: JSONPath, value: any, formatting
}
return withFormatting(text, edit, formattingOptions);
} else {
throw new Error('Array modification not supported yet');
if (value === void 0 && parent.children.length >= 0) {
//Removal
let removalIndex = lastSegment;
let toRemove = parent.children[removalIndex];
let edit: Edit;
if (parent.children.length === 1) {
// only item
edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
} else if (parent.children.length - 1 === removalIndex) {
// last item
let previous = parent.children[removalIndex - 1];
let offset = previous.offset + previous.length;
edit = { offset, length: parent.length - 2 - offset, content: '' };
} else {
edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
}
return withFormatting(text, edit, formattingOptions);
} else {
throw new Error('Array modification not supported yet');
}
}
} else {
throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);
......
......@@ -131,4 +131,29 @@ suite('JSON - edits', () => {
let edits = setProperty(content, [-1], 'bar', formatterOptions);
assertEdit(content, edits, '[\n 1,\n 2,\n "bar"\n]');
});
test('remove item in array with one item', () => {
let content = '[\n 1\n]';
let edits = setProperty(content, [0], void 0, formatterOptions);
assertEdit(content, edits, '[]');
});
test('remove item in the middle of the array', () => {
let content = '[\n 1,\n 2,\n 3\n]';
let edits = setProperty(content, [1], void 0, formatterOptions);
assertEdit(content, edits, '[\n 1,\n 3\n]');
});
test('remove last item in the array', () => {
let content = '[\n 1,\n 2,\n "bar"\n]';
let edits = setProperty(content, [2], void 0, formatterOptions);
assertEdit(content, edits, '[\n 1,\n 2\n]');
});
test('remove last item in the array if ends with comman', () => {
let content = '[\n 1,\n "foo",\n "bar",\n]';
let edits = setProperty(content, [2], void 0, formatterOptions);
assertEdit(content, edits, '[\n 1,\n "foo"\n]');
});
});
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册