@bhaireshm/binder
v1.0.0
Published
API Binder
Downloads
93
Readme
Binder
The Binder class implements the Binder interface, providing a singleton pattern implementation to manage and invoke functions dynamically by name. It is designed to store functions in a map and allows adding, retrieving, and executing these functions.
📦 Installation
# Install package globally
npm install -g @bhaireshm/binder@lastestFeatures
- Singleton Instance: Ensures that only one instance of Binder can exist.
- Function Management: Add, retrieve, and execute functions by name.
- Error Handling: Prevents duplicate function names and handles non-existent function calls.
Usage
Getting the Instance of the Binder class:
import {
Binder, // Singleton instance
BinderClass, // Class
} from "@bhaireshm/binder";
const binderRef = new Binder(); // Custom instanceAdding Functions to the Binder instance:
// Adding a single function
Binder.append("sum", (a: number, b: number) => a + b);
// Adding multiple functions
Binder.append({
subtract: (a: number, b: number) => a - b,
multiply: (a: number, b: number) => a * b,
});Retrieving and Calling Functions:
const sumFunction = Binder.get("sum");
const result = sumFunction(5, 3); // result will be 8
// Directly calling a function
const result = Binder.call("multiply", 5, 3); // result will be 15Listing Function names:
console.log(Binder.list()); // ["sum", "subtract", "multiply"]Piping multiple Function names:
const initialData = {
users: [],
// other properties
};
binder.pipe(["getUser", "cacheUserData"], initialData);Overriding Existing Functions:
// Overriding the "sum" function with a new implementation
Binder.override("sum", (a: number, b: number) => a * b);
// Now calling "sum" will use the new implementation
const result = Binder.call("sum", 5, 3); // result will be 15Error Handling
- Throws an error if trying to add a function with a name that already exists.
- Throws an error if trying to retrieve or call a non-existent function.
