What is mimic-fn?
The mimic-fn package is a utility that allows you to copy the properties of a function onto another function. This includes the function's name, length (the number of arguments it expects), and custom properties. It is useful when you want to wrap a function without losing its original properties, which can be important for debugging, introspection, and certain function-based APIs that rely on these properties.
What are mimic-fn's main functionalities?
Copying function properties
This feature allows you to copy all properties from the original function to the wrapper function, including the function name and custom properties.
const mimicFn = require('mimic-fn');
function original() {}
original.customProp = 'hello';
function wrapper() {
return original();
}
console.log(wrapper.name); // 'wrapper'
console.log(wrapper.customProp); // undefined
mimicFn(wrapper, original);
console.log(wrapper.name); // 'original'
console.log(wrapper.customProp); // 'hello'
Other packages similar to mimic-fn
rename-function
The rename-function package allows you to change the name of a function, which is one aspect of what mimic-fn does. However, it does not handle copying other properties or the function's length.
mimic-fn
Make a function mimic another one
Useful when you wrap a function in another function and like to preserve the original name and other properties.
Install
$ npm install mimic-fn
Usage
const mimicFn = require('mimic-fn');
function foo() {}
foo.unicorn = '🦄';
function wrapper() {
return foo() {};
}
console.log(wrapper.name);
mimicFn(wrapper, foo);
console.log(wrapper.name);
console.log(wrapper.unicorn);
API
It will copy over the properties name
, length
, displayName
, and any custom properties you may have set.
mimicFn(to, from)
Modifies the to
function and returns it.
to
Type: Function
Mimicking function.
from
Type: Function
Function to mimic.
Related
License
MIT © Sindre Sorhus