main.js (1965B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 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 PINF = require( '@stdlib/constants/float64/pinf' ); 24 var NINF = require( '@stdlib/constants/float64/ninf' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns an accumulator function which incrementally computes a mid-range. 32 * 33 * @returns {Function} accumulator function 34 * 35 * @example 36 * var accumulator = incrmidrange(); 37 * 38 * var midrange = accumulator(); 39 * // returns null 40 * 41 * midrange = accumulator( 3.14 ); 42 * // returns 3.14 43 * 44 * midrange = accumulator( -5.0 ); 45 * // returns ~-0.93 46 * 47 * midrange = accumulator( 10.1 ); 48 * // returns 2.55 49 * 50 * midrange = accumulator(); 51 * // returns 2.55 52 */ 53 function incrmidrange() { 54 var max = NINF; 55 var min = PINF; 56 var sum; 57 58 return accumulator; 59 60 /** 61 * If provided a value, the accumulator function returns an updated mid-range. If not provided a value, the accumulator function returns the current mid-range. 62 * 63 * @private 64 * @param {number} [x] - new value 65 * @returns {number} mid-range 66 */ 67 function accumulator( x ) { 68 if ( arguments.length === 0 ) { 69 if ( sum === void 0 ) { 70 return null; 71 } 72 return sum / 2.0; 73 } 74 if ( isnan( x ) ) { 75 min = x; 76 max = x; 77 } 78 if ( x > max ) { 79 max = x; 80 } 81 if ( x < min ) { 82 min = x; 83 } 84 sum = max + min; 85 return sum / 2.0; 86 } 87 } 88 89 90 // EXPORTS // 91 92 module.exports = incrmidrange;