Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Excerpt

Create a new function by wrapping an existing function in another existing function...

 

Syntax

The parameters to newFn are passed to innerFn. The return value of innerFn is passed as the sole parameter to outerFn (the wrapper) and the return value of outerFn is then passed to the calling script...

Code Block
themeRDark
languagejavascript
linenumberstrue
var newFn = outerFn.wraps(innerFn);
 
result = newFn(args...);

Parameters / Functions

Parameter / FunctionTypeMandatoryDescriptionAPI Version
innerFnFunction(tick)The inner function that will be called first with the arguments passed in to newFn1.0
outerFnFunction(tick)

The outer function that will be called second with a single argument that is the return value of innerFn.

(warning) outerFn should require only a single parameter as it's not possible for innerFn to return multiple arguments.

1.0
args...Variant(question)When calling newFn you can optionally specify one or more arguments that will be passed to innerFn1.0

Return value

ValueTypeDescriptionUtil.js version
newFnFunctionA new function based on the composition of innerFn and outerFn1.0
<result>Variant

The return value of the new function is derived as follows:

  1. Call innerFn with args
  2. Pass result of innerFn as the argument for outerFn
  3. Return outerFn's return value
1.0

Example

Code Block
themeRDark
languagejavascript
titleCreate a rounded square root function based on Math.sqrt and Math.round functions
linenumberstrue
var roundedSqRoot = Math.round.wraps(Math.sqrt);
 
roundedSqRoot(28); // 5
 
// Here's why:
// 1. Math.sqrt(528) → 5.291502622129181
// 2. Math.round(5.291502622129181) → 5
// 3. Return
value of Math.round then passed to calling script
Div
classbox
Availability
Status
colourGreen
titleStable

Requires:

Div
classbox
Contents

Jump to:

Table of Contents
maxLevel5

Div
classbox

Function Manipulation

Topics:

Child pages (Children Display)
alltrue
depthall
pageFunction Manipulation
excerpttrue

Div
classbox

See Also

Related pages:

  • Function Composition – the blog post that inspired the wraps() function in Util API
  • Hook API – create input/output hooks on any function