Last active
September 9, 2021 13:00
-
-
Save sranka23/e139462f937c50dfe7ffc30731df14f1 to your computer and use it in GitHub Desktop.
Object Builder (arrayToObjectParser) : Provided an array of strings, the program returns an output object with key in correct hierarchy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Author: Shourya Ranka | |
Objective : Provided an array of strings, the program returns an output object with key in correct hierarchy. | |
input : ["root", "root.user", "root.user.a", "root.a"] | |
output : { | |
root: { | |
a:{}, | |
user:{ | |
a:{} | |
} | |
} | |
} | |
*/ | |
const arrayToObjectParser = (arrayInput) => { | |
if(!arrayInput || !arrayInput.length){ | |
return {}; | |
} | |
let result = {}; | |
arrayInput.forEach(function(item, index){ | |
let itemsList = item.split("."); | |
if(itemsList.length > 1){ | |
result[itemsList[0]] = result[itemsList[0]] || {}; | |
let pointer = result[itemsList[0]]; | |
for(let i=1; i<itemsList.length;i++){ | |
pointer[itemsList[i]] = {}; | |
pointer = pointer[itemsList[i]]; | |
} | |
} | |
else{ | |
result[item] = {}; | |
} | |
}); | |
return result; | |
} | |
// Test 1 : Ideal case input | |
console.log(arrayToObjectParser(["root", "root.user", "root.user.a", "root.a"])); | |
// Test 2 : Input is empty | |
console.log(arrayToObjectParser([])); | |
// Test 3 : Input is invalid | |
console.log(arrayToObjectParser()); | |
// Test 4 : Parent item is not provided | |
console.log(arrayToObjectParser(["root.user", "root.user.a", "root.a"])); | |
// Test 5 : Only nested key is provided | |
console.log(arrayToObjectParser(["root.user.a"])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code Execution @ https://codepen.io/sranka2310/pen/VwWPqyL