Created
May 16, 2013 03:40
-
-
Save samma835/5589224 to your computer and use it in GitHub Desktop.
生成短链时,将ID转为高进制的数值,比如62进制(即包含字符’0′..’1′, ‘a’..’z', ‘A’..’Z')。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var generateShortLink = function(space, value) { | |
if (typeof value === 'number') { | |
var result = ''; | |
do { | |
result = space[value % space.length] + result; | |
value = Math.floor(value / space.length); | |
} while (value > 0) | |
} else if (typeof value === 'string') { | |
var result = 0; | |
for (var i = 0; i < value.length; ++i) { | |
result += space.indexOf(value[i]) * | |
Math.pow(space.length, value.length - i - 1); | |
} | |
} | |
return result; | |
}; | |
/* | |
$ generateShortLink('0123456789abcdef', 255) | |
'ff' | |
$ generateShortLink('01', 255) | |
'11111111' | |
$ generateShortLink('0123456789abcdefghijklmnopqrstuvwxyz', 123456789) | |
'21i3v9' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment