1 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
作為 的附加參數(shù),您必須跟蹤您的深度級(jí)別getPoint。將默認(rèn)值設(shè)置為 0,并在每次遞歸時(shí)遞增它。然后你可以為它逐級(jí)找到對(duì)應(yīng)的點(diǎn)。(我為 0 級(jí)插入了 1.0 系數(shù))。我還添加了評(píng)論以顯示每個(gè)級(jí)別的部分結(jié)果。
const data = [
{ id: 1, name: 'A', referer_id: null, point: 4 },
{ id: 2, name: 'B', referer_id: 1, point: 100 },
{ id: 3, name: 'C', referer_id: null, point: 4 },
{ id: 4, name: 'D', referer_id: 1, point: 2 },
{ id: 5, name: 'E', referer_id: null, point: 4 },
{ id: 6, name: 'F', referer_id: null, point: 4 },
{ id: 7, name: 'G', referer_id: 2, point: 4 }
];
const pointsByLevel = [1, 0.5, 0.3, 0.2]; // NOTE: I added a 1.0 for level 0
function getPoint(user_id, level = 0) {
const user = data.find((u) => u.id === user_id);
const mainUserPoint = user.point;
let sum = 0;
for (let subdep of data.filter((d) => d.referer_id === user_id)) {
let val = getPoint(subdep.id, level + 1);
sum += val;
}
let result = (mainUserPoint * pointsByLevel[level]) + sum;
console.log(`getPoint for ${user_id} "${user.name}" is ${level} levels deep and has the value ${result}`)
return result;
}
console.log(getPoint(1));
添加回答
舉報(bào)