1 | <img src="media/logo.svg" alt="mimic-fn" width="400">
|
2 | <br>
|
3 |
|
4 | > Make a function mimic another one
|
5 |
|
6 | Useful 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
|
17 | import mimicFunction from 'mimic-fn';
|
18 |
|
19 | function foo() {}
|
20 | foo.unicorn = '🦄';
|
21 |
|
22 | function wrapper() {
|
23 | return foo();
|
24 | }
|
25 |
|
26 | console.log(wrapper.name);
|
27 | //=> 'wrapper'
|
28 |
|
29 | mimicFunction(wrapper, foo);
|
30 |
|
31 | console.log(wrapper.name);
|
32 | //=> 'foo'
|
33 |
|
34 | console.log(wrapper.unicorn);
|
35 | //=> '🦄'
|
36 |
|
37 | console.log(String(wrapper));
|
38 | //=> '/* Wrapped with wrapper() */\nfunction foo() {}'
|
39 | ```
|
40 |
|
41 |
|
42 | ## API
|
43 |
|
44 | ### mimicFunction(to, from, options?)
|
45 |
|
46 | Modifies 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 |
|
54 | Type: `Function`
|
55 |
|
56 | Mimicking function.
|
57 |
|
58 | #### from
|
59 |
|
60 | Type: `Function`
|
61 |
|
62 | Function to mimic.
|
63 |
|
64 | #### options
|
65 |
|
66 | Type: `object`
|
67 |
|
68 | ##### ignoreNonConfigurable
|
69 |
|
70 | Type: `boolean`\
|
71 | Default: `false`
|
72 |
|
73 | 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.
|
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>
|