0

Given integers 0-24, I have to convert them to a polar theta in radians as a string. Ex: 0 = '0', 1 = 'pi/12', 2 = 'pi/6' etc. The pi should be an actual pi symbol. I think that my solution is inefficient. Here is what I do:

var fracStrings = ['0/1', '1/12', '1/6', '1/4', '1/3', '5/12', '1/2', '7/12', '2/3', '3/4', '5/6', '11/12', '1/1', '13/12', '7/6', '5/4', '4/3', '17/12', '3/2', '19/12', '5/3', '7/4', '11/6', '23/12', '2/1'];

function nToString(n){
     //converts angle to string representation
     var num = (fracStrings[n].split('/')[0] == 1) ? '' : fracStrings[n].split('/')[0];
     num = (fracStrings[n].split('/')[0] == 0) ? '0' : num + '\u03C0';
     var denom = (fracStrings[n].split('/')[1] == 1) ? '' : '/' + fracStrings[n].split('/')[1];
     return '' + num + denom;
 }

I find it inefficient to declare a fractions string. My problem is simplifying the fraction. I cannot have 12pi/12, I just need pi. Is there an efficient way to do this? This just hurts to look at.

FYI: \u03C0 is the pi symbol.

shurup
  • 751
  • 10
  • 33

1 Answers1

1

Put the pi symbol directly in the strings in the array.

const fracStrings = ['0', 'π/12', 'π/6', ...];

or

const fracStrings = ['0', '\u03C0/12', '\u03C0/6', ...];

Then the function is simple:

function nToString(n) {
    return fracStrings[n];
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks a lot! Do you think there's a way without initially defining a string? This still feels too hardcoded. Unfortunately, I could not find any libraries that can handle this fraction simplification. – shurup Aug 11 '18 at 01:39
  • 1
    Anything else is going to be complicated, because there's nothing built in to simplify fractions. If we were talking about an array of hundreds of items it might be worthwhile, but with only 24 elements the array is the best way. – Barmar Aug 11 '18 at 01:41
  • 1
    Here’s a really short function to simplify fractions: https://stackoverflow.com/questions/4652468/is-there-a-javascript-function-that-reduces-a-fraction – Ben West Aug 11 '18 at 02:23