Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sindresorhus/mimic-fn
Make a function mimic another one
https://github.com/sindresorhus/mimic-fn
Last synced: 3 months ago
JSON representation
Make a function mimic another one
- Host: GitHub
- URL: https://github.com/sindresorhus/mimic-fn
- Owner: sindresorhus
- License: mit
- Created: 2016-10-19T17:18:28.000Z (about 8 years ago)
- Default Branch: main
- Last Pushed: 2024-03-14T08:37:46.000Z (8 months ago)
- Last Synced: 2024-04-14T11:09:14.157Z (7 months ago)
- Language: JavaScript
- Size: 42 KB
- Stars: 90
- Watchers: 8
- Forks: 17
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license
- Security: .github/security.md
Awesome Lists containing this project
README
> Make a function mimic another one
Useful when you wrap a function in another function and you would like to preserve the original name and other properties.
## Install
```sh
npm install mimic-function
```## Usage
```js
import mimicFunction from 'mimic-function';function foo() {}
foo.unicorn = '🦄';function wrapper() {
return foo();
}console.log(wrapper.name);
//=> 'wrapper'mimicFunction(wrapper, foo);
console.log(wrapper.name);
//=> 'foo'console.log(wrapper.unicorn);
//=> '🦄'console.log(String(wrapper));
//=> '/* Wrapped with wrapper() */\nfunction foo() {}'
```## API
### mimicFunction(to, from, options?)
Modifies the `to` function to mimic the `from` function. Returns the `to` function.
`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied.
`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment.
#### to
Type: `Function`
Mimicking function.
#### from
Type: `Function`
Function to mimic.
#### options
Type: `object`
##### ignoreNonConfigurable
Type: `boolean`\
Default: `false`Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error.
## Related
- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function
- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name and other properties