time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

main.js (2169B)


      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 isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
     24 
     25 
     26 // MAIN //
     27 
     28 /**
     29 * Returns an accumulator function which incrementally computes an exponentially weighted mean.
     30 *
     31 * @param {NonNegativeNumber} alpha - smoothing factor
     32 * @throws {TypeError} must provide a nonnegative number
     33 * @throws {RangeError} must be on the interval `[0,1]`
     34 * @returns {Function} accumulator function
     35 *
     36 * @example
     37 * var accumulator = increwmean( 0.5 );
     38 *
     39 * var v = accumulator();
     40 * // returns null
     41 *
     42 * v = accumulator( 2.0 );
     43 * // returns 2.0
     44 *
     45 * v = accumulator( -5.0 );
     46 * // returns -1.5
     47 *
     48 * v = accumulator();
     49 * // returns -1.5
     50 */
     51 function increwmean( alpha ) {
     52 	var m;
     53 	if ( !isNonNegativeNumber( alpha ) ) {
     54 		throw new TypeError( 'invalid argument. Must provide a nonnegative number. Value: `' + alpha + '`.' );
     55 	}
     56 	if ( alpha < 0.0 || alpha > 1.0 ) {
     57 		throw new RangeError( 'invalid argument. Must provide a nonnegative number on the interval [0,1]. Value: `' + alpha + '`.' );
     58 	}
     59 	return accumulator;
     60 
     61 	/**
     62 	* If provided a value, the accumulator function returns an updated mean. If not provided a value, the accumulator function returns the current mean.
     63 	*
     64 	* @private
     65 	* @param {number} [x] - new value
     66 	* @returns {(number|null)} mean value or null
     67 	*/
     68 	function accumulator( x ) {
     69 		if ( arguments.length === 0 ) {
     70 			return ( m === void 0 ) ? null : m;
     71 		}
     72 		if ( m === void 0 ) {
     73 			m = x;
     74 		} else {
     75 			m += alpha * ( x-m );
     76 		}
     77 		return m;
     78 	}
     79 }
     80 
     81 
     82 // EXPORTS //
     83 
     84 module.exports = increwmean;