Skip to content

Instantly share code, notes, and snippets.

@Ghanshyam-K-Dobariya
Last active July 16, 2021 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ghanshyam-K-Dobariya/271b062e286deb229a98d20eeac63594 to your computer and use it in GitHub Desktop.
Save Ghanshyam-K-Dobariya/271b062e286deb229a98d20eeac63594 to your computer and use it in GitHub Desktop.
/*
what will be the o/p of this code ?
this was asked by one tech lead from fk.
*/
var testObj = {
bankId: 13,
accounts: [
{ accountName: "abc", currentBalance: { cash: 10 }, subAccounts: [] },
{
accountName: "bcd",
currentBalance: { cash: 20 },
subAccounts: [
{
accountName: "efg",
currentBalance: { cash: 30 },
subAccounts: [
{
accountName: "kge",
currentBalance: { cash: 40 },
subAccounts: [
{
accountName: "fsd",
currentBalance: { cash: 50 },
subAccounts: [],
},
],
},
],
},
{
accountName: "der",
currentBalance: { cash: 70 },
subAccounts: [
{
accountName: "fuh",
currentBalance: { cash: 80 },
subAccounts: [],
},
],
},
],
},
],
};
function findAvgSum(obj) {
const { accounts } = obj || {};
let sum = 0,
count = 0,
i,
item;
const runRecursion = (arr) => {
i = 0;
while (i < arr.length) {
item = arr[i] || {};
const { accountName, currentBalance, subAccounts = [] } = item;
console.log("accountName", accountName);
const { cash = 0 } = currentBalance || {};
sum += cash;
count++;
runRecursion(subAccounts);
i++;
}
};
runRecursion(accounts);
return sum / count;
}
console.log(findAvgSum(testObj));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment