Is there a JavaScript function that reduces a fraction

前端 未结 6 501
小鲜肉
小鲜肉 2020-12-02 12:08

say we have fraction 2/4, it can be reduced to 1/2.

Is there a JavaScript function that can do the reducing?

6条回答
  •  天涯浪人
    2020-12-02 12:54

    Here is a recursive function using ECMAScript 6 reduce. It works for most fractions as long as the remainder isn't too small. 0 has been redefined to make it work for arrays like [1.2, 2.4, 12, 24]. I tested in Chrome and IE Edge so it may behave differently in other browsers or upgrades. So it should work with an array of floats.

     Array.prototype.gcd = function () {
       if (this.length === 0)
         return null;
       return this.reduce((prev, curr) => {
         if (curr <= 1.00000000001e-12)
           return prev
         else
           return [curr, prev % curr].gcd();
        });
      }
    
      var reducedValueGCD = [1.2, 2.4, 12, 24, 240].gcd();
    

    Search for MDN reduce or more info here.

提交回复
热议问题