Skip to content

Commit

Permalink
implement setPath
Browse files Browse the repository at this point in the history
  • Loading branch information
LorisSigrist committed Oct 12, 2023
1 parent 5f0632c commit 70dfb7b
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/core/file-handling/formats/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,38 @@ export const JsonHandler = {
.run(content);

},
setPath() {
throw new Error("Not implemented");
setPath(oldJSON, key, value) {
oldJSON = oldJSON.trim().length > 0 ? oldJSON : "{}";
const obj = JSON.parse(oldJSON);


const path = key.split(".");

/**
*
* @param {any} tree
* @param {string[]} path
* @param {string} value
* @returns
*/
function setOnTree(tree, path, value) {
if (path.length === 1) {
tree[path[0]] = value;
return;
}

//Split the path into the current level and the rest of the path

const [current, ...rest] = path;
if (!current) throw new Error("Current is undefined. This should never happen");
if (!tree[current]) tree[current] = {};
setOnTree(tree[current], rest, value);
}


setOnTree(obj, path, value);

const newJSON = JSON.stringify(obj);
return newJSON;
},
};
40 changes: 40 additions & 0 deletions src/core/file-handling/formats/json.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,44 @@ describe("JsonHandler", () => {

expect(parseInvalid).toThrow(LoadingException);
});

it("sets a key on the top level", () => {
const oldObject = { key1: "value1", key2: "value2" };
const oldJSON = JSON.stringify(oldObject);

const newJSON = JsonHandler.setPath(oldJSON, "key3", "value3");
const newObject = JSON.parse(newJSON);

expect(newObject).toEqual({ ...oldObject, key3: "value3" });
});

it("sets a key if the original file is empty", () => {
const oldJSON = "";

const newJSON = JsonHandler.setPath(oldJSON, "newKey", "newValue");
const newObject = JSON.parse(newJSON);

expect(newObject).toEqual({ newKey: "newValue" });
});

it("sets a key on a deeply nested level", () => {
const oldObject = {
common: { save: "Save", cancel: "Cancel" },
home: { title: "Home" },
};

const oldJSON = JSON.stringify(oldObject);

const newJSON = JsonHandler.setPath(
oldJSON,
"home.subtitle.description",
"Subtitle"
);
const newObject = JSON.parse(newJSON);

expect(newObject).toEqual({
common: { save: "Save", cancel: "Cancel" },
home: { title: "Home", subtitle: { description: "Subtitle" } },
});
});
});

0 comments on commit 70dfb7b

Please sign in to comment.