logoTUSK

Patch

➕ Method: Patch

The patch method is the core feature of Tusk, allowing you to dynamically modify or extend methods at runtime. It’s designed to be safe, clean, and easy to use, making monkey patching a breeze! 🌬️


Differences Between 'original()' and 'original.call(this)'

  • Use original.call(this) when: The method depends on this, such as accessing object properties (this.value, this.name). Without call(this), this might be undefined, leading to errors.
  • Use original() when: The function does not rely on this, such as static functions (Math.max), standalone functions, or methods that only use passed arguments without referencing this.

Syntax

patch(target: Object, methodName: string, implementation: Function): void;

Parameters

PropTypeDefault
target
Object
-
methodName
string
-
implementation
Function
-

Usage Example

Extending Array Prototype with a flat Method

math.ts
import { patch } from "tusk";
 
patch(Array.prototype, "flat", function (original, depth) {
    const flattened = original.call(this, depth); 
    return flattened.map(() => 0); 
});
 
const map = [1, 2, 3, 4, 5];
const flattenedArray = map.flat();
console.log(flattenedArray); // Output: [0, 0, 0, 0]

Fixing a Third-Party library

Patch to avoid duplicates in insertMultiple

list.ts
import { patch } from "tusk";
 
import { ListManager } from "listner";
 
const oldManager = new ListManager();
oldManager.insertMultiple([{ id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }]);
oldManager.insertMultiple([{ id: 2, name: "Item 2" }, { id: 3, name: "Item 3" }]);
 
console.log(oldManager.getAll());
 
/*                                                                                   */
 
patch(ListManager.prototype, "insertMultiple", function(original, items) {
    const existingItems = this.getAll();
    const newItems = items.filter(item => 
        !existingItems.some(existing => existing.id === item.id)
    );
    if (newItems.length > 0) {
        original.call(this, newItems);
    }
});
 
const manager = new ListManager();
manager.insertMultiple([{ id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }]);
manager.insertMultiple([{ id: 2, name: "Item 2" }, { id: 3, name: "Item 3" }]);
 
console.log(manager.getAll());

Output

The item { id: 2, name: "Item 2" } was added again because there was no check to avoid duplicates in the original method.

terminal
[
    { id: 1, name: "Item 1" },
    { id: 2, name: "Item 2" },
    { id: 2, name: "Item 2" },
    { id: 3, name: "Item 3" }
]

🧠 Pro Tip ╺╸ Test your patches in a controlled environment before deploying to production to avoid unexpected side effects!

On this page