{"size": 1896, "ext": "js", "max_stars_repo_path": "packages/react-craft-ai-decision-tree/src/utils/utils.js", "max_stars_repo_name": "craft-ai/craft-ai-react-decision-tree", "max_stars_repo_stars_event_min_datetime": "2018-07-28T04:30:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T16:52:07.000Z", "max_issues_repo_path": "packages/react-craft-ai-decision-tree/src/utils/utils.js", "max_issues_repo_name": "craft-ai/craft-ai-react-decision-tree", "max_issues_repo_issues_event_min_datetime": "2017-08-23T09:18:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T20:36:20.000Z", "max_forks_repo_path": "packages/react-craft-ai-decision-tree/src/utils/utils.js", "max_forks_repo_name": "craft-ai/react-craft-ai-components", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 6, "max_issues_count": 23, "max_forks_count": null, "avg_line_length": 27.0857142857, "max_line_length": 77, "alphanum_fraction": 0.68407173}
import memoize from 'lodash/memoize';
import { mix } from 'polished';
import {
  COLOR_LEAVES_CONFIDENCE_0,
  COLOR_LEAVES_CONFIDENCE_1,
  COLOR_LEAVES_CONFIDENCE_UNDEFINED,
  NODE_PATH_SEPARATOR
} from './constants';

export function computeLeafColor(confidence) {
  if (confidence != null) {
    const blend = Math.pow(confidence, 3);
    return mix(blend, COLOR_LEAVES_CONFIDENCE_1, COLOR_LEAVES_CONFIDENCE_0);
  }
  return COLOR_LEAVES_CONFIDENCE_UNDEFINED;
}

export function findSelectedNode(path, tree) {
  let pathArray = path.split(NODE_PATH_SEPARATOR);
  // making the root node an exception
  if (path == '0') {
    return tree;
  }
  else {
    // remove the first element of the path because it is the root path;
    return findSelectedNodeRecursion(pathArray.slice(1), tree, {});
  }
}

function findSelectedNodeRecursion(path, tree, decisionRules) {
  // adding decision rules of the node
  if (tree.decision_rule) {
    if (decisionRules[tree.decision_rule.property]) {
      decisionRules[tree.decision_rule.property].push({
        operator: tree.decision_rule.operator,
        operand: tree.decision_rule.operand
      });
    }
    else {
      decisionRules[tree.decision_rule.property] = [
        {
          operator: tree.decision_rule.operator,
          operand: tree.decision_rule.operand
        }
      ];
    }
  }
  if (path.length !== 0) {
    const indexChild = parseInt(path[0]);
    return findSelectedNodeRecursion(
      path.slice(1),
      tree.children[indexChild],
      decisionRules
    );
  }
  else {
    tree.decisionRules = decisionRules;
    return tree;
  }
}

export const computeSamplesCount = memoize((dtNode) => {
  const selfCount = (dtNode.prediction && dtNode.prediction.nb_samples) || 0;
  const children = dtNode.children || [];
  return children.reduce(
    (count, child) => count + computeSamplesCount(child),
    selfCount
  );
});
