Skip to content

Instantly share code, notes, and snippets.

@Pito1992
Last active January 11, 2023 14:35
Show Gist options
  • Select an option

  • Save Pito1992/08029c216921995eb8f57a903bb0172d to your computer and use it in GitHub Desktop.

Select an option

Save Pito1992/08029c216921995eb8f57a903bb0172d to your computer and use it in GitHub Desktop.
Employee Importance
test_employees_1 = [[1,5,[2,3]],[2,3,[]],[3,3,[]]]; // id = 1 11
test_employees_2 = [[1,7,[2,3]],[2,1,[]],[3,2,[4]],[4,3,[]]]; // id = 1
test_employees_3 = [[1,2,[5]],[5,-3,[]]]; // id = 5 -3
test_employees_4 = [[1,10,[2,3,4]],[2,-1,[]],[3,-2,[]],[4,-3,[]]]; // id = 3 -2
function mapEmployeesToObj(arrEmployees) {
const employeeObj = arrEmployees.reduce((acc, item) => {
const id = item[0];
const value = item?.[1] ?? 0;
const subIds = item?.[2] ?? null;
return {
...acc,
[id]: {
value,
subIds
}
}
}, {})
return employeeObj;
}
const handleImportanceValue = function(employees, startId) {
const employeeObj = mapEmployeesToObj(employees);
const rootEmployee = employeeObj[startId]
if (rootEmployee) {
const calcImportanceValue = function({ value, subIds }) {
let result = 0;
subIds.forEach(subId => {
const employee = employeeObj[subId];
result += calcImportanceValue(employee);
})
return result + value;
}
return calcImportanceValue(rootEmployee)
}
return startId;
}
console.log(handleImportanceValue(test_employees_1, 1));
console.log(handleImportanceValue(test_employees_2, 1));
console.log(handleImportanceValue(test_employees_3, 5));
console.log(handleImportanceValue(test_employees_4, 3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment