ES6 class and fractions

Denis Voronin
2 min readJul 10, 2019

On one project it was necessary to carry out calculations with fractions. Gradually, the project began to appear scattered functions for working with fractions. In the end, we decided to combine all this into one class. Fraction has a divisor and a denominator, so we will pass these two arguments to create a class.

/**
* @constructor
* @param {number} nominator
* @param {number} denominator
*/
constructor(nominator, denominator) {
/** @private */
this
._nominator = nominator;
/** @private */
this
._denominator = denominator;
}

Perhaps this is enough, but we wanted the class to create fractions not only from numbers but also from strings, an object or an array. To do this, we write the parsing function. To work with this class, we wrote a facade in which there is a method of parsing.

The parse function expects an array with one or two elements, for the remaining cases an exception will be thrown.

If we have only one element in the array, then we expect an instance of a fraction, or a string, an object, an array. For each case, we write checks to throw an exception if the data is not correct. If we have two elements, then we think that numbers or strings have arrived, if not, we throw an exception.

Now we can start working with fractions. How about addition? If the denominators are different, then we bring the fractions to a common denominator. To find a common denominator, we need to multiply the denominators and divide by the largest common divider.

Below you will see the addition method with additional utilities for finding the common denominator, the largest common divisor and modulus division function.

As you may have noticed, the search for the largest common divisor occurs according to Euclid’s algorithm. Also, you probably noticed the fraction reduction method.

We call the class method, which creates a new reduced fraction using the reduced function. The logic of this function is simple — we look for the greatest common divisor in the nominator and denominator and divide them.

With subtraction, multiplication and division, everything is much simpler.

Subtraction is also addition, only the second fraction is now negative :-)

When multiplying, we reduce fractions, then multiply their nominators and denominators, and reduce the resulting fraction again.

When dividing, we swap the numerator and denominator in the second fraction and simply multiply the fractions.

In the facade of the class, we implemented several additional methods, for example, checking the shares of several fractions, as a result of which we will receive an answer whether the fraction obtained is an integer or not.

All code can be viewed on GitHub.

--

--