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

Add a new method called extend to dynamically create and attach methods to objects #2

Open
ofabiodev opened this issue Mar 1, 2025 · 0 comments

Comments

@ofabiodev
Copy link
Owner

Warning

Before implementing the extend method, a solution must be found to inject the new method directly into the target object's type definition. Without this, TypeScript (or other type-checking systems) may throw errors indicating that the method does not exist. This is critical to ensure type safety and a seamless developer experience.

The new extend method will allow users to dynamically add new methods to existing objects or classes without modifying or overriding existing methods. Unlike patch, which changes the behavior of existing methods, extend is designed to enhance objects by adding entirely new functionality. This method will provide a clean and safe way to extend objects at runtime, making it ideal for adding utility methods or custom logic without risking unintended side effects.

Example Usage:

The extend method will be used to add new methods to objects, as shown below:

extend(Math, "reset", function() {
  return 0; // Custom logic for the new method
});

// Usage of the newly added method
console.log(Math.reset()); // Output: 0

Key Difference from patch:

  • patch: Modifies or overrides existing methods.

    patch(Array.prototype, "flat", function (original, depth) {
      const flattened = original.call(this, depth); 
      return flattened.map(() => 0); // Changes behavior of `flat`
    });
  • extend: Adds new methods without altering existing ones.

    extend(Math, "reset", function() {
      return 0; // Adds a new method `reset` to `Math`
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant