So what i want to acheive is that, i will add the child selector values to the parent selector. so these are just the two selectors i’m using to test, they can be more and different too. When i switch the postions of the child and parent the algorithm doesn’t seem to work.. is there a way to fix this?
this code works as expected
const ecommerceObj = {
'header#section-header > div > div.Header__FlexItem.Header__FlexItem--fill.hidden-phone > nav > ul > li:nth-child(6) > a':
{
revenue: 4,
sessions: 3,
},
'header#section-header > div > div.Header__FlexItem.Header__FlexItem--fill.hidden-phone > nav > ul > li:nth-child(6) > a > span':
{
revenue: 6,
sessions: 8,
},
};
function generateRollUpValues(ecommerceObj) {
const getParent = (str) => {
const idx = String(str).lastIndexOf(' > ');
if (idx > 0) {
return str.substr(0, idx);
}
return false;
};
const rollup = {};
const rev = [];
const keys = Object.keys(ecommerceObj);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < keys.length; i++) {
rev.push(keys[i]);
}
for (let t = rev.length - 1; t >= 0; t -= 1) {
const key = rev[t];
const current = ecommerceObj[key];
const p = getParent(key);
// console.log(key + ' -> ' + p);
if (p && rollup[p] === undefined) {
rollup[p] = {
revenue: 0,
sessions: 0,
};
}
if (rollup[key] != undefined) {
ecommerceObj[key].revenue += rollup[key].revenue;
ecommerceObj[key].sessions += rollup[key].sessions;
}
if (p) {
rollup[p].revenue += ecommerceObj[key].revenue;
rollup[p].sessions += ecommerceObj[key].sessions;
}
}
return ecommerceObj;
}
console.log(generateRollUpValues(ecommerceObj));
but this doesn’t work
const ecommerceObj = {
'header#section-header > div > div.Header__FlexItem.Header__FlexItem--fill.hidden-phone > nav > ul > li:nth-child(6) > a > span':
{
revenue: 6,
sessions: 8,
},
'header#section-header > div > div.Header__FlexItem.Header__FlexItem--fill.hidden-phone > nav > ul > li:nth-child(6) > a':
{
revenue: 4,
sessions: 3,
},
};
>Solution :
function generateRollUpValues(ecommerceObj) {
const getParent = (str) => {
const idx = String(str).lastIndexOf(' > ');
if (idx > 0) {
return str.substr(0, idx);
}
return false;
};
const rollup = {};
const rev = [];
const keys = Object.keys(ecommerceObj);
// eslint-disable-next-line no-plusplus
keys.forEach(key => {
rev.push(key);
});
rev.sort();
for (let t = rev.length - 1; t >= 0; t -= 1) {
const key = rev[t];
const current = ecommerceObj[key];
const parent = getParent(key);
// console.log(key + ' -> ' + parent);
if (parent && rollup[parent] === undefined) {
rollup[parent] = {
revenue: 0,
sessions: 0,
};
}
if (rollup[key] != undefined) {
ecommerceObj[key].revenue += rollup[key].revenue;
ecommerceObj[key].sessions += rollup[key].sessions;
}
if (parent) {
rollup[parent].revenue += ecommerceObj[key].revenue;
rollup[parent].sessions += ecommerceObj[key].sessions;
}
}
return ecommerceObj;
}