all files / src/ext/ math.js

66.67% Statements 18/27
33.33% Branches 4/12
100% Functions 2/2
66.67% Lines 18/27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58            1×   1× 1× 1× 1×           1×             2×     2× 2×   2× 2× 2× 2× 2× 2× 2×   2×                             2×        
/*!
 * Copyright (C) 2017 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-transpiler/graphs/contributors
 * @url http://glayzzle.com
 */
'use strict';
module.exports = function($php) {
 
  const PHP_ROUND_HALF_UP     = $php.constant('PHP_ROUND_HALF_UP');
  const PHP_ROUND_HALF_DOWN   = $php.constant('PHP_ROUND_HALF_DOWN');
  const PHP_ROUND_HALF_EVEN   = $php.constant('PHP_ROUND_HALF_EVEN');
  const PHP_ROUND_HALF_ODD    = $php.constant('PHP_ROUND_HALF_ODD');
 
  /**
   * http://php.net/manual/en/function.round.php
   * @url http://phpjs.org/functions/round/
   */
  $php.context.function.declare(
    '\\round', [
      {name: 'val', type: 'float'},
      {name: 'precision', type: 'int', default: 0},
      {name: 'mode', type: 'mode', default: PHP_ROUND_HALF_UP}
    ],
    'float', function round(value, precision, mode) {
      Iif (typeof precision === 'undefined') {
        precision = 0;
      }
      Eif (typeof mode === 'undefined') {
        mode = PHP_ROUND_HALF_UP;
      }
      var m, f, isHalf, sgn; // helper variables
      precision |= 0; // making sure precision is integer
      m = Math.pow(10, precision);
      value *= m;
      sgn = (value > 0) | -(value < 0); // sign of the number
      isHalf = value % 1 === 0.5 * sgn;
      f = Math.floor(value);
 
      Iif (isHalf) {
        switch (mode) {
          case PHP_ROUND_HALF_DOWN:
            value = f + (sgn < 0); // rounds .5 toward zero
            break;
          case PHP_ROUND_HALF_EVEN:
            value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
            break;
          case PHP_ROUND_HALF_ODD:
            value = f + !(f % 2); // rounds .5 towards the next odd integer
            break;
          default:
            value = f + (sgn > 0); // rounds .5 away from zero
        }
      }
      return (isHalf ? value : Math.round(value)) / m;
    }
  );
};