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.

Revisions

  1. Pito1992 revised this gist Jan 11, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.js
    Original file line number Diff line number Diff line change
    @@ -43,4 +43,4 @@ const handleImportanceValue = function(employees, 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, -2));
    console.log(handleImportanceValue(test_employees_4, 3));
  2. Pito1992 created this gist Jan 11, 2023.
    46 changes: 46 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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, -2));