d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Javascript Problem: Turn An Object Into A Graph > 100 Fg
Add Reply New Topic New Poll
Member
Posts: 14,925
Joined: Jan 3 2008
Gold: 135,879.75
Nov 17 2019 04:50pm
Given this object:

Code
const graph = {
folderA: {
folderB: {
fileA,
fileB
},
fileC,
fileD,
folderC: {
fileE,
folderF
}
}
}


Turn it into the below graph.

Code
folderA
|
|--- folderB
| |
| |
| |--- fileA
| |
| |--- fileB
|
|
|--- fileC
|
|--- fileD
|
|--- folderC
| |
| |
| |--- fileE
| |
| |---f olderF ... et cetera

Stipulations:

The vertical lines should be placed at the middle of the above word.

For this reason, folderB and folderC have their vertical bars placed correctly, whereas folderA is off by 1 space.

If the word has even-number letters, for example 'folder', the vertical lines should be placed at l.

Your algorithm should be able to satisfy an object of any sized nesting.

Please do not pm me the answer, just post it in here. Payout will go to the first working answer.

This post was edited by kdog3682 on Nov 17 2019 04:52pm
Member
Posts: 2,619
Joined: May 21 2004
Gold: 21,934.00
Nov 27 2019 03:36pm
your object isn't valid JS. You can't have keys that aren't assigned.

So for example this:

Code
folderB: {
fileA,
fileB
},


Throws an error. Did you mean for this to be an array of either filenames(single string) or folder (folder name as the key, the values are an array of files or folders)?

I would usually write your object as an array like the following, except in any real world environment, you would usually get back an array of objects instead of a mixed array.

Code
const graphArray = [
{
'name': 'folderA',
children: [
{
name: 'folderAB',
children: [
'fileAA',
'fileAB'
]
},
'fileAC',
'fileAD',
{
name: 'folderAC',
children: [
'fileAE',
{
name: 'folderAF',
children: []
}
]
}
]
}
];


Otherwise, this is what your original object looks like but made to be valid:

Code

folderA: {
folderAB: {
fileAA: 'file.aa',
fileAB: 'file.ab'
},
fileAC: 'file.ac',
fileAD: 'file.ad',
folderAC: {
fileAE: 'file.ae',
folderAF: {}
}
},


This post was edited by frixionburne on Nov 27 2019 03:37pm
Member
Posts: 14,925
Joined: Jan 3 2008
Gold: 135,879.75
Nov 27 2019 07:33pm
fileA would have contents: 'fileA' , fileB would have contents: 'fileB'

et cetera.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll