Is there a JavaScript function that reduces a fraction

前端 未结 6 500
小鲜肉
小鲜肉 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 13:03

    Reduce a string fraction like "2/4" and output as string fraction.

    function reduce([numerator, denominator]){
      for (let i = numerator; i > 0; i--) {
        if(!(numerator % i) && !(denominator % i)){
          return [(numerator / i), (denominator / i)];
        }
      }
    }
    
    function reduceFraction(string){
      return reduce(string.split('/').map(n => +n)).join('/');
    }
    
    one = '2/4';
    two = '20/200';
    three = '330/2050';
    
    console.log('2/4 reduced to', reduceFraction(one));
    console.log('20/200 reduced to', reduceFraction(two));
    console.log('330/2050 reduced to', reduceFraction(three));

提交回复
热议问题