Last active
July 16, 2021 06:56
-
-
Save Ghanshyam-K-Dobariya/271b062e286deb229a98d20eeac63594 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
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