time-to-botec

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

absdiff.js (1873B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2021 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 incrmean = require( './../../incr/mean' );
     24 var abs = require( '@stdlib/math/base/special/abs' );
     25 
     26 
     27 // MAIN //
     28 
     29 /**
     30 * Calculates the absolute difference of the values and the respective group means for the elements of a numeric array.
     31 *
     32 * @private
     33 * @param {Array} x - input array
     34 * @param {Array} groups - array of group labels
     35 * @param {Array} levels - array of distinct group levels
     36 * @returns {Array} array of absolute centered values
     37 *
     38 * @example
     39 * var x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
     40 * var groups = [ 'a', 'b', 'a', 'a', 'b', 'b', 'a', 'a', 'b', 'b' ];
     41 * var levels = [ 'a', 'b' ];
     42 * var out = absMeanDiff( x, groups, levels );
     43 * // returns [ ~3.6, 4.4, ..., ~3.6 ]
     44 */
     45 function absMeanDiff( x, groups, levels ) {
     46 	var accumulators = {};
     47 	var means = {};
     48 	var len = x.length;
     49 	var out = [];
     50 	var i;
     51 	for ( i = 0; i < levels.length; i++ ) {
     52 		accumulators[ levels[ i ] ] = incrmean();
     53 	}
     54 	for ( i = 0; i < len; i++ ) {
     55 		accumulators[ groups[ i ] ]( x[ i ] );
     56 	}
     57 	for ( i = 0; i < levels.length; i++ ) {
     58 		means[ levels[ i ] ] = accumulators[ levels[ i ] ]();
     59 	}
     60 	for ( i = 0; i < len; i++ ) {
     61 		out.push( abs( x[ i ] - means[ groups[ i ] ] ) );
     62 	}
     63 	return out;
     64 }
     65 
     66 
     67 // EXPORTS //
     68 
     69 module.exports = absMeanDiff;