Wrap a function without changing its name and other properties.
Function wrappers return a new function which means the original function's
name and other properties are usually lost. This module enhances them to keep
those properties instead.
The new function will also print the original function's body when stringified.
Function wrappers are commonly used in functional programming. They take a
function as input and return it wrapped. Examples include
memoizing or ensuring a function is
only called once.
Example
import keepFuncProps from 'keep-func-props'// Any function wrapper worksimport memoize from 'lodash/memoize.js'const betterMemoize = keepFuncProps(memoize)const anyFunction = () => true// Function `name` and other properties are keptconsole.log(anyFunction) // `[Function: anyFunction]`console.log(memoize(anyFunction)) // `[Function: memoized]`console.log(betterMemoize(anyFunction)) // `[Function: anyFunction]`// Function body is kept when stringifiedconsole.log(String(anyFunction))// () => trueconsole.log(String(
Install
npm install keep-func-props
This package works in both Node.js >=18.18.0 and
browsers.
import keepFuncProps from 'keep-func-props'// Any function wrapper worksconst wrapper = (anyFunction) => (...args) => anyFunction(...args)// `betterWrapper` is like `wrapper` but it keeps the function propertiesconst betterWrapper = keepFuncProps(wrapper)
keepFuncProps(wrapper)
wrapper: (anyFunction, [...args]) => newFunction Returns: new wrapper
A function wrapper is passed as argument. A copy of it is returned.
See also
mimic-function: same but
for functions that do not wrap other functions.