Skip to content

#7588 Refactor rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) function to reduce its Cognitive Complexity from 53 to the 15 allowed. - #8570

Merged
AlexeyGirin merged 2 commits into
masterfrom
copilot/refactor-rxnmerge-function
Nov 19, 2025
Merged

AlexeyGirin merged 2 commits into
masterfrom
copilot/refactor-rxnmerge-function

Conversation

Copilot AI commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor

How the feature works? / How did you fix the issue?

The rxnMerge function had a cognitive complexity of 53 (allowed: 15) due to deeply nested loops, conditionals, and an inline helper function. Refactored by extracting 10 focused helper functions:

Core Logic Extraction:

  • calculateAverageBondLength() / rescaleMolecules() - Bond length normalization
  • getFragmentType() / categorizeMolecules() - Molecule classification (reactants/products/agents)
  • shiftMol() - Positioned as module-level function instead of inline closure

Layout & Rendering:

  • layoutReactionFragments() / mergeWithoutLayout() - Conditional positioning logic
  • addPlusSigns() / aggregateBoundingBoxes() - UI element placement
  • createReactionArrow() - Arrow positioning with fallback handling

Result:

// Before: 187 lines, complexity 53
function rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) {
  // 8 nested loops, 6 conditional chains, inline functions...
}

// After: 34 lines, complexity ~3
function rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) {
  const ret = new Struct();
  
  if (SHOULD_RESCALE_MOLECULES) rescaleMolecules(mols);
  
  const { bbReact, bbAgent, bbProd, molReact, molAgent, molProd } =
    categorizeMolecules(mols, nReactants, nProducts);
  
  if (shouldReactionRelayout) {
    layoutReactionFragments(ret, molReact, bbReact, molAgent, bbAgent, molProd, bbProd);
  } else {
    mergeWithoutLayout(ret, molReact, molAgent, molProd);
  }
  
  addPlusSigns(ret, bbReact);
  addPlusSigns(ret, bbProd);
  
  const bbReactAll = aggregateBoundingBoxes(bbReact);
  const bbProdAll = aggregateBoundingBoxes(bbProd);
  
  ret.rxnArrows.add(createReactionArrow(bbReactAll, bbProdAll));
  ret.isReaction = true;
  return ret;
}

Check list

  • unit-tests written
  • e2e-tests written
  • documentation updated
  • PR name follows the pattern #1234 – issue name
  • branch name doesn't contain '#'
  • PR is linked with the issue
  • base branch (master or release/xx) is correct
  • task status changed to "Code review"
  • reviewers are notified about the pull request
Original prompt

This section details on the original issue you should resolve

<issue_title>Refactor rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) function to reduce its Cognitive Complexity from 53 to the 15 allowed.</issue_title>
<issue_description>Problem: Refactor rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) function to reduce its Cognitive Complexity from 53 to the 15 allowed.
Cognitive Complexity of functions should not be too high

Why is this an issue?
Cognitive Complexity is a measure of how hard it is to understand the control flow of a unit of code. Code with high cognitive complexity is hard to read, understand, test, and modify.

As a rule of thumb, high cognitive complexity is a sign that the code should be refactored into smaller, easier-to-manage pieces.
Which syntax in code does impact cognitive complexity score?

Here are the core concepts:

  • Cognitive complexity is incremented each time the code breaks the normal linear reading flow.
    This concerns, for example, loop structures, conditionals, catches, switches, jumps to labels, and conditions mixing multiple operators.
  • Each nesting level increases complexity.
    During code reading, the deeper you go through nested layers, the harder it becomes to keep the context in mind.
  • Method calls are free
    A well-picked method name is a summary of multiple lines of code. A reader can first explore a high-level view of what the code is performing then go deeper and deeper by looking at called functions content.
    Note: This does not apply to recursive calls, those will increment cognitive score.

The method of computation is fully detailed in the pdf

Note that the calculation of cognitive complexity at function level deviates from the documented process. Given the functional nature of JavaScript, nesting functions is a prevalent practice, especially within frameworks like React.js. Consequently, the cognitive complexity of functions remains independent from one another. This means that the complexity of a nesting function does not increase with the complexity of nested functions.
What is the potential impact?

Developers spend more time reading and understanding code than writing it. High cognitive complexity slows down changes and increases the cost of maintenance.

How can I fix it?

Noncompliant code example
The code is using a complex condition and has a cognitive cost of 3.

function calculateFinalPrice(user, cart) {
  let total = calculateTotal(cart);
  if (user.hasMembership                       // +1 (if)
    && user.orders > 10                        // +1 (more than one condition)
    && user.accountActive
    && !user.hasDiscount
    || user.orders === 1) {                    // +1 (change of operator in condition)
      total = applyDiscount(user, total);
  }
  return total;
}

Compliant solution
Even if the cognitive complexity of the whole program did not change, it is easier for a reader to understand the code of the calculateFinalPrice function, which now only has a cognitive cost of 1.

function calculateFinalPrice(user, cart) {
  let total = calculateTotal(cart);
  if (isEligibleForDiscount(user)) {       // +1 (if)
    total = applyDiscount(user, total);
  }
  return total;
}

function isEligibleForDiscount(user) {
  return user.hasMembership
    && user.orders > 10                     // +1 (more than one condition)
    && user.accountActive
    && !user.hasDiscount
    || user.orders === 1                    // +1 (change of operator in condition)
}

Problem location:

  1. packages/ketcher-core/src/domain/serializers/mol/utils.js:138
    </issue_description>

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

- Extract bond length calculation into calculateAverageBondLength()
- Extract molecule rescaling into rescaleMolecules()
- Extract fragment type determination into getFragmentType()
- Extract molecule categorization into categorizeMolecules()
- Move shiftMol helper to module level
- Extract layout logic into layoutReactionFragments()
- Extract merge logic into mergeWithoutLayout()
- Extract plus sign addition into addPlusSigns()
- Extract bounding box aggregation into aggregateBoundingBoxes()
- Extract arrow creation logic into createReactionArrow()

The main rxnMerge function now orchestrates these helper functions,
making the code flow easier to read and reducing cognitive complexity.

Co-authored-by: AlexeyGirin <26869421+AlexeyGirin@users.noreply.github.com>
Copilot AI changed the title [WIP] Refactor rxnMerge function to reduce cognitive complexity Refactor rxnMerge to reduce cognitive complexity from 53 to 3 Nov 18, 2025
Copilot AI requested a review from AlexeyGirin November 18, 2025 15:18
@AlexeyGirin
AlexeyGirin marked this pull request as ready for review November 18, 2025 16:21
@AlexeyGirin AlexeyGirin changed the title Refactor rxnMerge to reduce cognitive complexity from 53 to 3 #7588 Refactor rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) function to reduce its Cognitive Complexity from 53 to the 15 allowed. Nov 18, 2025
@AlexeyGirin
AlexeyGirin requested review from rrodionov91 and removed request for AlexeyGirin, NataliaLoginova and Zhirnoff November 18, 2025 16:21
@AlexeyGirin
AlexeyGirin merged commit 4902fcf into master Nov 19, 2025
33 of 37 checks passed
@AlexeyGirin
AlexeyGirin deleted the copilot/refactor-rxnmerge-function branch November 19, 2025 13:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor rxnMerge(mols, nReactants, nProducts, nAgents, shouldReactionRelayout) function to reduce its Cognitive Complexity from 53 to the 15 allowed.

3 participants