ndarray.js (2108B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 24 25 26 // MAIN // 27 28 /** 29 * Calculates the range of a strided array via a callback function. 30 * 31 * @param {PositiveInteger} N - number of indexed elements 32 * @param {Collection} x - input array/collection 33 * @param {integer} stride - index increment 34 * @param {NonNegativeInteger} offset - starting index 35 * @param {Callback} clbk - callback 36 * @param {*} [thisArg] - execution context 37 * @returns {number} range 38 * 39 * @example 40 * var x = [ -2.0, 1.0, 3.0, -5.0, 4.0, 0.0, -1.0, -3.0 ]; 41 * 42 * function accessor( v ) { 43 * return v * 2.0; 44 * } 45 * 46 * var v = rangeBy( x.length, x, 1, 0, accessor ); 47 * // returns 18.0 48 */ 49 function rangeBy( N, x, stride, offset, clbk, thisArg ) { 50 var max; 51 var min; 52 var ix; 53 var v; 54 var i; 55 56 if ( N <= 0 ) { 57 return NaN; 58 } 59 if ( N === 1 || stride === 0 ) { 60 v = clbk.call( thisArg, x[ 0 ], 0, 0, x ); 61 if ( v === void 0 || isnan( v ) ) { 62 return NaN; 63 } 64 return 0.0; 65 } 66 ix = offset; 67 for ( i = 0; i < N; i++ ) { 68 min = clbk.call( thisArg, x[ ix ], i, ix, x ); 69 if ( min !== void 0 ) { 70 break; 71 } 72 ix += stride; 73 } 74 if ( i === N ) { 75 return NaN; 76 } 77 max = min; 78 i += 1; 79 for ( i; i < N; i++ ) { 80 ix += stride; 81 v = clbk.call( thisArg, x[ ix ], i, ix, x ); 82 if ( v === void 0 ) { 83 continue; 84 } 85 if ( isnan( v ) ) { 86 return v; 87 } 88 if ( v < min ) { 89 min = v; 90 } else if ( v > max ) { 91 max = v; 92 } 93 } 94 return max - min; 95 } 96 97 98 // EXPORTS // 99 100 module.exports = rangeBy;