开发者

Implementing URL shortener logic in JavaScript

开发者 https://www.devze.com 2023-04-07 17:34 出处:网络
As a result of finding this interesting question, I decided to write an example in JavaScript which implemented the logic and contribute it back to the question. The problem is that I\'m having some i

As a result of finding this interesting question, I decided to write an example in JavaScript which implemented the logic and contribute it back to the question. The problem is that I'm having some issues implementing the logic. I can speak Ruby which is开发者_StackOverflow what I'm basing my implementation on, but I'm having an issue with an endless while loop which I'm having trouble sorting out.

I have the whole implementation up on js.do.it here: http://jsdo.it/rfkrocktk/k9Jq

function encode(i) {
   if (i == 0) return DICTIONARY[0];

   var result = '';
   var base = DICTIONARY.length;

   while (i > 0) {
       result += DICTIONARY[i % base];
       i = i / base;
   }

   result = result.reverse();
   return result;
}

What am I doing wrong here?


Javascript uses floating point math by default. Use i = Math.floor(i / base);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号