Skip to content

Instantly share code, notes, and snippets.

@sebastien-p
Forked from 140bytes/LICENSE.txt
Created August 24, 2011 16:13
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save sebastien-p/1168420 to your computer and use it in GitHub Desktop.
Save sebastien-p/1168420 to your computer and use it in GitHub Desktop.
base62 encode
function (
a, // positive base10 encoded integer
b, // placeholder for result
c // placeholder for modulo
) {
for (
a = a !== +a || a % 1 ? -1 : a, b = ""; // if not a base10 integer, 'a' will be '-1'
// for example, '.5 % 1 == .5' but '1 % 1 == 0'
a >= 0; // also prevents the user to use negative base10 integers
a = Math.floor(a / 62) || -1 // using a bitwise hack here will fail with great numbers
)
// a%62 -> 0-61
// 0-9 | 36-61 | 10-35
// 48-57 | 65-90 | 97-121
// 0-9 | A-Z | a-z
b = String.fromCharCode(((c = a % 62) > 9 ? c > 35 ? 29 : 87 : 48) + c) + b;
return b // will return either an empty or a base62-encoded string
}
function(a,b,c){for(a=a!==+a||a%1?-1:a,b="";a>=0;a=Math.floor(a/62)||-1)b=String.fromCharCode(((c=a%62)>9?c>35?29:87:48)+c)+b;return b}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Sebastien P. https://twitter.com/#!/_sebastienp
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "base62 encode",
"description": "A JavaScript implementation of base62 encode.",
"keywords": [
"base62",
"encode",
"integer",
"number",
"string"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>140bytes</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var base62encode = function(a,b,c){for(a=a!==+a||a%1?-1:a,b="";a>=0;a=Math.floor(a/62)||-1)b=String.fromCharCode(((c=a%62)>9?c>35?29:87:48)+c)+b;return b};
document.getElementById("ret").innerHTML = base62encode(3748986303764)
</script>
@sebastien-p
Copy link
Author

Yeehaa, finally a = a !== +a || a % 1 ? -1 : a and a >= 0 did the trick !

135 bytes including input value validation and support for great numbers :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment