min_by.js (2142B)
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 var isNegativeZero = require( '@stdlib/math/base/assert/is-negative-zero' ); 25 26 27 // MAIN // 28 29 /** 30 * Calculates the minimum value of a strided array via a callback function. 31 * 32 * @param {PositiveInteger} N - number of indexed elements 33 * @param {Collection} x - input array/collection 34 * @param {integer} stride - index increment 35 * @param {Callback} clbk - callback 36 * @param {*} [thisArg] - execution context 37 * @returns {number} minimum value 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 = minBy( x.length, x, 1, accessor ); 47 * // returns -10.0 48 */ 49 function minBy( N, x, stride, clbk, thisArg ) { 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 ) { 61 return NaN; 62 } 63 return v; 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 i += 1; 81 for ( i; i < N; i++ ) { 82 ix += stride; 83 v = clbk.call( thisArg, x[ ix ], i, ix, x ); 84 if ( v === void 0 ) { 85 continue; 86 } 87 if ( isnan( v ) ) { 88 return v; 89 } 90 if ( v < min || ( v === min && isNegativeZero( v ) ) ) { 91 min = v; 92 } 93 } 94 return min; 95 } 96 97 98 // EXPORTS // 99 100 module.exports = minBy;