Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): add support for built-in types in deepCopy #2691

Conversation

derevnjuk
Copy link
Contributor

@derevnjuk derevnjuk commented May 1, 2024

Information

Type Breaking change
Fix No

Todos

  • Tests
  • Coverage

closes #2690

Summary by CodeRabbit

  • Refactor
    • Enhanced the deepClone function for more efficient handling of various data types including maps, sets, arrays, and buffer types.
    • Improved handling of property descriptors and prototype chains during object cloning.
  • New Features
    • Introduced new properties and methods in Base and Test classes to enhance functionality.
  • Tests
    • Added comprehensive tests for cloning complex data structures, circular references, and various special objects like buffers and typed arrays.

@derevnjuk derevnjuk self-assigned this May 1, 2024
Copy link

coderabbitai bot commented May 1, 2024

Walkthrough

The deepClone function has been enhanced to accurately clone complex data structures like Set, Map, and typed arrays, while also improving the handling of circular references and property descriptors. Changes to class structures and additional test cases enhance the robustness of the utility.

Changes

File Path Change Summary
.../deepClone.ts Refactored to arrow function, enhanced data type handling
.../objects/deepClone.spec.ts Added extensive test cases for new clone capabilities
.../objects/isBuffer.ts Removed import as isBuffer is no longer used
.../src/utils/objects/Base.ts Added properties and methods to class Base
.../src/utils/objects/Test.ts Updated class Test with new properties and constructor

Assessment against linked issues

Objective Addressed Explanation
Properly clone Set and Map, preserving behavior (#2690)
Update deepClone to handle circular references and various data types efficiently (#2690)

🐰 A Poem by CodeRabbit

In the burrow of code, where the carrots are stowed,
A function was tweaked, now it flawlessly cloned.
Maps and Sets, in their intricate nets,
Now replicate without frets, in the tests they are vets.
🌟 With each line refined, the code does shine,
A hop, skip, and a jump, in the digital vine. 🌿


Recent Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between a29a3fe and c459aa8.
Files selected for processing (2)
  • packages/core/src/utils/objects/deepClone.spec.ts (5 hunks)
  • packages/core/src/utils/objects/deepClone.ts (3 hunks)
Additional comments not posted (5)
packages/core/src/utils/objects/deepClone.spec.ts (5)

Line range hint 26-68: Ensure comprehensive testing of cloning functionality.

This script verifies that the test case "should clone object" is present in all files where deepClone is used, ensuring comprehensive testing.


Line range hint 71-91: Good coverage for circular reference scenarios.

This test case effectively checks the cloning functionality for objects with circular references, ensuring that deepClone handles such cases correctly.


Line range hint 92-108: Validate buffer cloning within custom classes.

This script verifies that the test case "should clone a buffer" is present in all files where deepClone is used, ensuring comprehensive testing.


109-122: Excellent test coverage for cloning Map, Set, and Array.

This test case effectively checks the cloning functionality for Map, Set, and Array within a custom class, ensuring that deepClone handles these data structures correctly.


123-129: Ensure accurate cloning of typed arrays.

This script verifies that the test case "should clone typed arrays" is present in all files where deepClone is used, ensuring comprehensive testing.

Verification successful

The verification process has confirmed that the test case "should clone typed arrays" is correctly implemented in the file deepClone.spec.ts and does not appear to be duplicated or incorrectly implemented in other parts of the codebase where deepClone is used. This aligns with the review comment's intent to ensure accurate cloning of typed arrays.

  • File: packages/core/src/utils/objects/deepClone.spec.ts - The test case is correctly implemented and unique to this file.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `deepClone` function correctly clones typed arrays as specified in the test case "should clone typed arrays".

# Find files that import the deepClone module and search within those files.
rg --files-with-matches --type typescript $'import {deepClone} from "./deepClone"' | while read file; do
  # Test: Search for the test case to find omissions. Expect: Matches.
  ast-grep --lang typescript --pattern $'describe("deepClone", {
    $$$
    it("should clone typed arrays", {
      $$$
    })
  })' "$file"
done

Length of output: 223



Script:

#!/bin/bash
# Description: Verify that the `deepClone` function correctly clones typed arrays as specified in the test case "should clone typed arrays".

# Find files that import the deepClone module and search within those files.
rg --files-with-matches --type typescript 'import \{deepClone\} from "\./deepClone"' | while read file; do
  # Test: Search for the test case to find omissions. Expect: Matches.
  ast-grep --lang typescript --pattern $'describe("deepClone", {
    $$$
    it("should clone typed arrays", {
      $$$
    })
  })' "$file"
done

Length of output: 133



Script:

#!/bin/bash
# Description: Verify that the `deepClone` function correctly clones typed arrays as specified in the test case "should clone typed arrays".

# Find files that import the deepClone module and search within those files.
rg --files-with-matches 'import \{deepClone\} from "\./deepClone"' | while read file; do
  # Test: Search for the test case to find omissions. Expect: Matches.
  ast-grep --lang typescript --pattern $'describe("deepClone", {
    $$$
    it("should clone typed arrays", {
      $$$
    })
  })' "$file"
done

Length of output: 275


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Out of diff range and nitpick comments (1)
packages/core/src/utils/objects/deepClone.ts (1)

Line range hint 16-85: Refactor deepClone to improve readability and maintainability.

- export const deepClone = (source: any, stack = new WeakMap()): any => {
+ export const deepClone = (source: any, stack = new WeakMap<any, any>()): any => {
  // provides an early exit for simple cases
  if (isBasicType(source)) {
    return source;
  }

  const stacked = stack.get(source);
  if (stacked) {
    // See issue #1619
    return stacked;
  }

  if (ArrayBuffer.isView(source)) {
    return Buffer.isBuffer(source)
      ? Buffer.from(source)
      : // adds support for all kind of TypedArray such as Int8Array, Uint8Array, etc
        new (classOf(source))(source.buffer.slice(0), source.byteOffset, source.byteLength);
  }

  if (isDate(source)) {
    return new Date(source);
  }

  if (isRegExp(source)) {
    return new RegExp(source);
  }

  if (Array.isArray(source)) {
    const clone: unknown[] = [];
    stack.set(source, clone);
    source.forEach((item, idx) => (clone[idx] = deepClone(item, stack)));
    return clone;
  }

  if (source instanceof Map) {
    const clone = new Map();
    stack.set(source, clone);
    source.forEach((value, key) => clone.set(deepClone(key, stack), deepClone(value, stack)));
    return clone;
  }

  if (source instanceof Set) {
    const clone = new Set();
    stack.set(source, clone);
    source.forEach((value) => clone.add(deepClone(value, stack)));
    return clone;
  }

  const clone = Object.create(Reflect.getPrototypeOf(source));
  stack.set(source, clone);

  Reflect.ownKeys(source).forEach((key) => {
    // respects property descriptors and the prototype chain more explicitly, which is important for objects with getter/setter.
    const descriptor = Object.getOwnPropertyDescriptor(source, key);

    if (descriptor) {
      if (!isFunction(descriptor.value)) {
        Object.defineProperty(clone, key, {
          ...descriptor,
          value: deepClone(descriptor.value, stack)
        });
      } else {
        Object.defineProperty(clone, key, descriptor);
      }
    }
  });

  return clone;
};

Suggest breaking down the function into smaller, more manageable functions, each handling a specific type of data structure. This will improve readability and maintainability.

@derevnjuk derevnjuk requested a review from Romakita May 2, 2024 04:26
@Romakita
Copy link
Collaborator

Romakita commented May 3, 2024

@derevnjuk perfect ;)

@Romakita Romakita merged commit d0cf855 into tsedio:production May 3, 2024
15 checks passed
@derevnjuk derevnjuk deleted the fix-#2690/deepClone-does-not-respect-built-in-objects-like-Set-and-Map branch May 3, 2024 09:08
@Romakita
Copy link
Collaborator

Romakita commented May 3, 2024

🎉 This PR is included in version 7.68.4 🎉

The release is available on:

Your semantic-release bot 📦🚀

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.

[BUG] deepClone does not respect built-in objects like Set and Map
2 participants