UNPKG

2.08 kBMarkdownView Raw
1<img src="media/logo.svg" alt="mimic-fn" width="400">
2<br>
3
4> Make a function mimic another one
5
6Useful when you wrap a function in another function and like to preserve the original name and other properties.
7
8## Install
9
10```
11$ npm install mimic-fn
12```
13
14## Usage
15
16```js
17import mimicFunction from 'mimic-fn';
18
19function foo() {}
20foo.unicorn = '🦄';
21
22function wrapper() {
23 return foo();
24}
25
26console.log(wrapper.name);
27//=> 'wrapper'
28
29mimicFunction(wrapper, foo);
30
31console.log(wrapper.name);
32//=> 'foo'
33
34console.log(wrapper.unicorn);
35//=> '🦄'
36
37console.log(String(wrapper));
38//=> '/* Wrapped with wrapper() */\nfunction foo() {}'
39```
40
41
42## API
43
44### mimicFunction(to, from, options?)
45
46Modifies the `to` function to mimic the `from` function. Returns the `to` function.
47
48`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied.
49
50`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment.
51
52#### to
53
54Type: `Function`
55
56Mimicking function.
57
58#### from
59
60Type: `Function`
61
62Function to mimic.
63
64#### options
65
66Type: `object`
67
68##### ignoreNonConfigurable
69
70Type: `boolean`\
71Default: `false`
72
73Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error.
74
75## Related
76
77- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function
78- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name and other properties
79
80---
81
82<div align="center">
83 <b>
84 <a href="https://tidelift.com/subscription/pkg/npm-mimic-fn?utm_source=npm-mimic-fn&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
85 </b>
86 <br>
87 <sub>
88 Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
89 </sub>
90</div>