Skip to content

feat: add array/base/for-each #5319

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 159 additions & 0 deletions lib/node_modules/@stdlib/array/base/for-each/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<!--

@license Apache-2.0

Copyright (c) 2025 The Stdlib Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->

# forEach

> Invoke a callback funcion once for each array element.

<!-- Section to include introductory text. Make sure to keep an empty line after the intro `section` element and another before the `/section` close. -->

<section class="intro">

</section>

<!-- /.intro -->

<!-- Package usage documentation. -->

<section class="usage">

## Usage

```javascript
var forEach = require( '@stdlib/array/base/for-each' );
```

#### forEach( x, fcn\[, thisArg] )

Invokes a callback function once for each array element.

```javascript
var naryFunction = require( '@stdlib/utils/nary-function' );
var log = require( '@stdlib/console/log' );

var x = [ 1, 2, 3, 4 ];

forEach( x, naryFunction( log, 1 ) );
```

The function accepts the following arguments:

- **x**: input array.
- **fcn**: callback to apply.
- **thisArg**: callback execution context _(optional)_.

To set the callback function execution context, provide a `thisArg`.

<!-- eslint-disable no-invalid-this -->

```javascript
function accumulate( z ) {
this.sum += z;
}

var x = [ 1, 2, 3, 4 ];

var ctx = {
'sum': 0
};

forEach( x, accumulate, ctx );
var sum = ctx.sum;
// returns 10
```

The callback function is provided the following arguments:

- **value**: current array element.
- **index**: current array element index.
- **arr**: the input array.

</section>

<!-- /.usage -->

<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="notes">

## Notes

- If provided an array-like object having a `forEach` method, the function defers execution to that method and assumes that the method API has the following signature:

```text
x.forEach( fcn, thisArg )
```

- The function support array-like objects having getter and setter accessors for array element access (e.g., [`@stdlib/array/base/accessor`][@stdlib/array/base/accessor]).

</section>

<!-- /.notes -->

<!-- Package usage examples. -->

<section class="examples">

## Examples

<!-- eslint no-undef: "error" -->

```javascript
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var naryFunction = require( '@stdlib/utils/nary-function' );
var log = require( '@stdlib/console/log' );
var forEach = require( '@stdlib/array/base/for-each' );

var x = discreteUniform( 10, 0, 10, {
'dtype': 'float64'
});

forEach( x, naryFunction( log, 1 ) );
```

</section>

<!-- /.examples -->

<!-- Section to include cited references. If references are included, add a horizontal rule *before* the section. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="references">

</section>

<!-- /.references -->

<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->

<section class="related">

</section>

<!-- /.related -->

<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="links">

[@stdlib/array/base/accessor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array/base/accessor

</section>

<!-- /.links -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* @license Apache-2.0
*
* Copyright (c) 2025 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var zeroTo = require( '@stdlib/array/base/zero-to' );
var pkg = require( './../package.json' ).name;
var forEach = require( './../lib' );


// FUNCTIONS //

/**
* Callback invoked for each ndarray element.
*
* @private
* @param {number} value - array element
* @throws {Error} unexpected error
*/
function clbk( value ) {
if ( isnan( value ) ) {
throw new Error( 'unexpected error' );
}
}

/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x = zeroTo( len );
return benchmark;

/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var i;

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
forEach( x, clbk );
if ( isnan( x[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( x[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}


// MAIN //

/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;

min = 1; // 10^min
max = 6; // 10^max

for ( i = min; i <= max; i++ ) {
len = pow( 10, i );

f = createBenchmark( len );
bench( pkg+':dtype=generic,len='+len, f );
}
}

main();
36 changes: 36 additions & 0 deletions lib/node_modules/@stdlib/array/base/for-each/docs/repl.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

{{alias}}( x, fcn[, thisArg] )
Invoke a callback function once for each array element.

The callback function is provided the following arguments:

- value: current array element.
- index: current array element index.
- arr: the input array.

If provided an array-like object having a `forEach` method , the function
defers execution to that method and assumes that the method has the
following signature:

x.forEach( clbk, thisArg )

Parameters
----------
x: Array|TypedArray|Object
Input array.

fcn: Function
Callback function.

thisArg: any (optional)
Callback function execution context.

Examples
--------
> var x = [ 1, 2, 3, 4 ];
> function f( v ) { if ( v !== v ) { throw new Error( '...' ); } };
> {{alias}}( x, f );

See Also
--------

Loading