Create Rational Number - Node.js Data Structure

Node.js examples for Data Structure:Rational Number

Description

Create Rational Number

Demo Code


// copyright (c) 2014 dqdb

function Rational(a, b)
{
  this.a = a;//from   w w  w .ja  va 2  s  .c  o m
  this.b = b || 1; // to avoid division by zero
}

Rational.prototype.simplify = function()
{
  var g = Math.gcd(this.a, this.b);
  return new Rational(this.a / g, this.b / g);
};

Rational.prototype.toDouble = function()
{
  return this.a / this.b;
};

Rational.prototype.toFixed = function(digits)
{
  return (this.a / this.b).toFixed(digits);
};

Rational.prototype.toString = Rational.prototype.toFormatted = function(digits)
{
  return this.toDouble().toFormatted(digits === undefined ? 3 : digits);
};

Rational.prototype.rebase = function(base)
{
  return new Rational(this.a * base / this.b, base);
};

Math.gcd = function(a, b)
{
  a = Math.abs(a);
  b = Math.abs(b);
  if (a == 0)
    return b;
  
  while (b)
  {
    if (a > b)
      a = a - b;
    else
      b = b - a;
  }
    
  return a;
};

if (!Math.trunc)
{
  Math.trunc = function(a)
  {
    return a >= 0 ? Math.floor(a) : Math.ceil(a);
  };
}

Number.removeTrailingZeros = /\.?0+$/;

Number.prototype.toFormatted = function(digits)
{
  var value = this.toFixed(digits);
  return value.indexOf(".") == -1 ? value : value.replace(Number.removeTrailingZeros, "");
};

Related Tutorials