https://github.com/stdlib-js/utils-decorate-after
Decorate a provided function such that the function's return value is provided as an argument to another function.
https://github.com/stdlib-js/utils-decorate-after
decorate decorator fcn fun func function functional javascript node node-js nodejs stdlib transform util utilities utils
Last synced: 6 months ago
JSON representation
Decorate a provided function such that the function's return value is provided as an argument to another function.
- Host: GitHub
- URL: https://github.com/stdlib-js/utils-decorate-after
- Owner: stdlib-js
- License: apache-2.0
- Created: 2022-08-17T21:03:22.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2024-12-30T05:06:27.000Z (9 months ago)
- Last Synced: 2025-04-12T13:40:12.855Z (6 months ago)
- Topics: decorate, decorator, fcn, fun, func, function, functional, javascript, node, node-js, nodejs, stdlib, transform, util, utilities, utils
- Language: JavaScript
- Homepage: https://github.com/stdlib-js/stdlib
- Size: 800 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Citation: CITATION.cff
- Security: SECURITY.md
Awesome Lists containing this project
README
About stdlib...
We believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we've built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.
The library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.
When you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.
To join us in bringing numerical computing to the web, get started by checking us out on GitHub, and please consider financially supporting stdlib. We greatly appreciate your continued support!
# decorateAfter
[![NPM version][npm-image]][npm-url] [![Build Status][test-image]][test-url] [![Coverage Status][coverage-image]][coverage-url]
> Decorate a provided function such that the function's return value is provided as an argument to another function.
## Installation
```bash
npm install @stdlib/utils-decorate-after
```Alternatively,
- To load the package in a website via a `script` tag without installation and bundlers, use the [ES Module][es-module] available on the [`esm`][esm-url] branch (see [README][esm-readme]).
- If you are using Deno, visit the [`deno`][deno-url] branch (see [README][deno-readme] for usage intructions).
- For use in Observable, or in browser/node environments, use the [Universal Module Definition (UMD)][umd] build available on the [`umd`][umd-url] branch (see [README][umd-readme]).The [branches.md][branches-url] file summarizes the available branches and displays a diagram illustrating their relationships.
To view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.
## Usage
```javascript
var decorateAfter = require( '@stdlib/utils-decorate-after' );
```#### decorateAfter( fcn, arity, after\[, thisArg] )
Decorates a provided function such that the function's return value is provided as an argument to another function.
```javascript
var abs = require( '@stdlib/math-base-special-abs' );function negate( v ) {
return -v;
}var f = decorateAfter( abs, abs.length, negate );
// returnsvar bool = ( abs.length === f.length );
// returns truevar v = f( -5 );
// returns -5v = f( 5 );
// returns -5
```Decorators are intended to be transparent, meaning that, when interfacing with an API, the decorated API should have the same signature (i.e., number of parameters) as the decorated function. Thus, a typical value for `arity` is `fcn.length`. This function does not require equality, however, and the `arity` argument is allowed to diverge from that of the decorated function. Specifying a differing `arity` does **not** affect function evaluation behavior, as the returned function passes all provided arguments to the decorated function.
```javascript
var abs = require( '@stdlib/math-base-special-abs' );function negate( v ) {
return -v;
}var f = decorateAfter( abs, 0, negate );
// returnsvar bool = ( abs.length === f.length );
// returns falsevar v = f( -5 );
// returns -5v = f( 5 );
// returns -5
```To specify the function execution context for `after`, provide a `thisArg` argument.
```javascript
var abs = require( '@stdlib/math-base-special-abs' );function counter() {
this.count += 1;
}var ctx = {
'count': 0
};var f = decorateAfter( abs, abs.length, counter, ctx );
// returnsvar v = f( -5 );
// returns 5v = f( 5 );
// returns 5var count = ctx.count;
// returns 2
```#### decorateAfter.factory( fcn, arity, after\[, thisArg] )
Uses code generation to decorate a provided function such that the function's return value is provided as an argument to another function.
```javascript
var abs = require( '@stdlib/math-base-special-abs' );function negate( v ) {
return -v;
}var f = decorateAfter.factory( abs, abs.length, negate );
// returnsvar bool = ( abs.length === f.length );
// returns truevar v = f( -5 );
// returns -5v = f( 5 );
// returns -5
```Argument behavior is the same as for `decorateAfter` above.
## Notes
- If the `after` function returns `undefined`, the returned decorator returns the return value of the decorated function `fcn`; otherwise, the returned decorator returns the return value of `after`.
- Code generation may be problematic in browser contexts enforcing a strict [content security policy][mdn-csp] (CSP). If running in or targeting an environment with a CSP, avoid using code generation.
- For non-native functions, the code generation API supports returning a decorator whose API exactly matches the API of the decorated function, including function length and parameter names. For native functions, due to how native functions serialize to strings, the code generation API generates placeholder parameter names, which are unlikely to match the canonical parameter names. Using placeholder parameter names ensures that the length of the decorator (i.e., number of parameters) matches the decorated function and, except in scenarios involving function source code inspection, will not affect runtime behavior.
- For the non-code generation API, the returned decorator supports an `arity` less than or equal to `10` (i.e., the maximum arity of the returned function is `10`). For an arity greater than `10`, the returned function has an arity equal to `0`. While this violates strict notions of a decorator, for all practical purposes, this is unlikely to be an issue, as the vast majority of functions have fewer than `10` parameters and the need for explicitly checking function length is relatively uncommon.
- The decorators returned by the code generation and non-code generation APIs should have the same performance characteristics, and, thus, neither API should have a performance advantage over the other. The main advantage of the code generation API is the ability to return a decorator whose signature exactly matches the signature of a non-native decorated function.
- Common use cases for decorating a function with additional actions **after** invocation include logging, capturing invocation statistics, and validating return values.## Examples
```javascript
var discreteUniform = require( '@stdlib/random-base-discrete-uniform' );
var format = require( '@stdlib/string-format' );
var decorateAfter = require( '@stdlib/utils-decorate-after' );function count() {
this.count += 1;
}function greet() {
return 'Hello!';
}function randstr( f ) {
var str;
var i;str = [];
for ( i = 0; i < discreteUniform( 1, 10 ); i++ ) {
str.push( f() );
}
return str.join( ' ' );
}// Create an evaluation context to allow tracking how many times a function is invoked:
var ctx = {
'count': 0
};// Decorate a function with a counter:
var f = decorateAfter( greet, greet.length, count, ctx );// Generate a random greeting:
var str = randstr( f );
// returns// Check how many times the function was invoked:
var c = ctx.count;
// returns
```* * *
## Notice
This package is part of [stdlib][stdlib], a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.
For more information on the project, filing bug reports and feature requests, and guidance on how to develop [stdlib][stdlib], see the main project [repository][stdlib].
#### Community
[![Chat][chat-image]][chat-url]
---
## License
See [LICENSE][stdlib-license].
## Copyright
Copyright © 2016-2024. The Stdlib [Authors][stdlib-authors].
[npm-image]: http://img.shields.io/npm/v/@stdlib/utils-decorate-after.svg
[npm-url]: https://npmjs.org/package/@stdlib/utils-decorate-after[test-image]: https://github.com/stdlib-js/utils-decorate-after/actions/workflows/test.yml/badge.svg?branch=main
[test-url]: https://github.com/stdlib-js/utils-decorate-after/actions/workflows/test.yml?query=branch:main[coverage-image]: https://img.shields.io/codecov/c/github/stdlib-js/utils-decorate-after/main.svg
[coverage-url]: https://codecov.io/github/stdlib-js/utils-decorate-after?branch=main[chat-image]: https://img.shields.io/gitter/room/stdlib-js/stdlib.svg
[chat-url]: https://app.gitter.im/#/room/#stdlib-js_stdlib:gitter.im[stdlib]: https://github.com/stdlib-js/stdlib
[stdlib-authors]: https://github.com/stdlib-js/stdlib/graphs/contributors
[umd]: https://github.com/umdjs/umd
[es-module]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules[deno-url]: https://github.com/stdlib-js/utils-decorate-after/tree/deno
[deno-readme]: https://github.com/stdlib-js/utils-decorate-after/blob/deno/README.md
[umd-url]: https://github.com/stdlib-js/utils-decorate-after/tree/umd
[umd-readme]: https://github.com/stdlib-js/utils-decorate-after/blob/umd/README.md
[esm-url]: https://github.com/stdlib-js/utils-decorate-after/tree/esm
[esm-readme]: https://github.com/stdlib-js/utils-decorate-after/blob/esm/README.md
[branches-url]: https://github.com/stdlib-js/utils-decorate-after/blob/main/branches.md[stdlib-license]: https://raw.githubusercontent.com/stdlib-js/utils-decorate-after/main/LICENSE
[mdn-csp]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP