range_by.js (2096B)
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 {Callback} clbk - callback 35 * @param {*} [thisArg] - execution context 36 * @returns {number} range 37 * 38 * @example 39 * var x = [ -2.0, 1.0, 3.0, -5.0, 4.0, 0.0, -1.0, -3.0 ]; 40 * 41 * function accessor( v ) { 42 * return v * 2.0; 43 * } 44 * 45 * var v = rangeBy( x.length, x, 1, accessor ); 46 * // returns 18.0 47 */ 48 function rangeBy( N, x, stride, clbk, thisArg ) { 49 var max; 50 var min; 51 var ix; 52 var v; 53 var i; 54 55 if ( N <= 0 ) { 56 return NaN; 57 } 58 if ( N === 1 || stride === 0 ) { 59 v = clbk.call( thisArg, x[ 0 ], 0, 0, x ); 60 if ( v === void 0 || isnan( v ) ) { 61 return NaN; 62 } 63 return 0.0; 64 } 65 if ( stride < 0 ) { 66 ix = (1-N) * stride; 67 } else { 68 ix = 0; 69 } 70 for ( i = 0; i < N; i++ ) { 71 min = clbk.call( thisArg, x[ ix ], i, ix, x ); 72 if ( min !== void 0 ) { 73 break; 74 } 75 ix += stride; 76 } 77 if ( i === N ) { 78 return NaN; 79 } 80 max = min; 81 i += 1; 82 for ( i; i < N; i++ ) { 83 ix += stride; 84 v = clbk.call( thisArg, x[ ix ], i, ix, x ); 85 if ( v === void 0 ) { 86 continue; 87 } 88 if ( isnan( v ) ) { 89 return v; 90 } 91 if ( v < min ) { 92 min = v; 93 } else if ( v > max ) { 94 max = v; 95 } 96 } 97 return max - min; 98 } 99 100 101 // EXPORTS // 102 103 module.exports = rangeBy;