0

I got one working function from google, but I can't understand it. I need to also write the reverse function

Can someone explain the logic? Both the calculation of how AA becomes 26 and the syntax if you would...

This one: when you input 27 it gives you aa

function idOf(i) {
    return (i >= 26 ? idOf((i / 26 >> 0) - 1) : '') +  'abcdefghijklmnopqrstuvwxyz'[i % 26 >> 0];
}
黎蕙欣
  • 49
  • 5
  • 1
    You might want to ask [the original author](https://stackoverflow.com/a/32007970/1048572). I guess that's where you got the code from, right? – Bergi Mar 28 '18 at 18:41
  • 1
    The recursion seems to be quite straightforward. What part do you not understand about it? Also can you evaluate `idOf(27)` step-by-step with pen and paper? Try that. – Bergi Mar 28 '18 at 18:44
  • 1
    Yeah I should ask the original author. But then I am worry that the post was 7 years ago... – 黎蕙欣 Mar 28 '18 at 18:44
  • Can someone explain the syntax at least? Like I don't understand what is the ? and >> and : in the return statement. – 黎蕙欣 Mar 28 '18 at 18:45
  • `idOf(27)` gives the result `"ab"`, not `"aa"` – Douglas Tyler Gordon Mar 28 '18 at 18:45
  • Have a look at whether [this](https://stackoverflow.com/a/42988003/1048572) is easier to understand. – Bergi Mar 28 '18 at 18:47
  • `i / 26 >> 0` is divide `i` by 26 and take the integer value by using a right bitshift of zero bits. the equivalent is `Math.floor(i / 26)`. the difference is bitshifting uses 32 bit numbers where as numbers have 64 bit float – Nina Scholz Mar 28 '18 at 18:48
  • @Bergi how could you find that link? I am impressed – messerbill Mar 28 '18 at 18:54
  • 1
    @messerbill Simple: I wrote the answer :-) Or if you refer to the first link, I tried to [search for the name of the function](https://stackoverflow.com/search?q=idOf%20[js]) – Bergi Mar 28 '18 at 18:55
  • Check this https://repl.it/repls/ShyTenderChief ,I hope it will give you a clue how does it work – RidgeA Mar 28 '18 at 18:56
  • @Bergi ok, i understand this explanation :D – messerbill Mar 28 '18 at 18:56
  • @Bergi thank you i've had no idea about that search functionality :O – messerbill Mar 28 '18 at 18:59

1 Answers1

1

Ok, lets break it down.

(i >= 26 ? idOf((i / 26 >> 0) - 1) : '')

If i is bigger than 25, the function will recursively call itself. If its smaller than 26, it will return an empty string

'?' is a ternary operator. You could kind of translate that to

if (i= 26) { return idOf((i / 26 >> 0) - 1) } else { return '' }

Next section:

+  'abcdefghijklmnopqrstuvwxyz'[i % 26 >> 0]

This will get the letter at the x position of the string, x being (i % 26 >> 0) and add it to the string from the previous part

i % 26 >> 0 seems to be just getting the remaind of i % 26. If you want to read about this operator, checkout MDN

iagowp
  • 2,093
  • 1
  • 19
  • 28