Following task: You've got an array which contains parts. Parts can contain subparts. Subparts can contain further subparts and so on.
For example:
computer
cpu
hardDisc
graphicsCard
graphicsCardCpu
graphicsCardRam
Let's suppose I have a correct structure where every part has a unique id. Such a structure would be assured.
I've made this function which retrieves a part with a given id from the above described structure.
// Example structure
var structure = [
{
id : 1,
name : 'firstLevelOne',
category : 'alpha',
subParts : null,
},
{
id : 2,
name : 'firstLevelTwo',
category : 'beta',
subParts : [{
id : 6,
name : 'secondLevelOne',
category : 'alpha',
subParts : null
}],
},
{
id : 3,
name : 'firstLevelThree',
category : 'alpha',
subParts : [{
id : 7,
name : 'secondLevelTwo',
category : 'gamma',
subParts : [{
id : 8,
name : 'thirdLevelOne',
category : 'beta',
subParts : [ {
id: 11,
name : 'fourthLevelOne',
category : 'alpha',
subParts : null
}]
},
{
id : 10,
name : 'secondLevelFour',
category : 'beta',
subParts : null
}]
}],
},
{
id : 4,
name : 'firstLevelFour',
category : 'gamma',
subParts : [{
id : 9,
name : 'secondLevelThree',
category : 'alpha',
subParts : null
}],
},
{
id : 5,
name : 'firstLevelFive',
category : 'beta',
subParts : null,
}
];
// #### Let's try this out ...
var part = getPart(4, structure);
for (var i in part) {
console.log(part[i]);
}
console.log('\n');
part = getPart(11, structure);
for (var i in part) {
console.log(part[i]);
}
console.log('\n');
part = getPart(8, structure);
for (var i in part) {
console.log(part[i]);
}
// ############################
// The actual function ...
// Retrieves the object from
// the storage-array.
function getPart(id, arr) {
var ret = null;
var i;
if (!id || !arr) return ret;
for (i = 0; i < arr.length; i++) {
if (arr[i]['id'] === id) {
return arr[i];
} else {
if (arr[i]['subParts']) {
ret = getPart(id, arr[i]['subParts']);
if (ret) return ret;
}
}
};
return ret;
}
Are there weak points? Could the function be improved?