Last active
December 10, 2015 12:15
-
-
Save nexpr/8455aca943073e88b23b to your computer and use it in GitHub Desktop.
This file contains 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
function basetrans(srcchars, dstchars){ | |
var srcbase = isUnique(srcchars) && baseNum(srcchars, false), | |
dstbase = isUnique(dstchars) && baseNum(dstchars, true), | |
srcbase_bitlen = Math.log2(srcbase), | |
dstbase_bitlen = Math.log2(dstbase) | |
if(!srcbase || !dstbase){ | |
throw new Error("argument string is not unique chars") | |
} | |
if(!srcbase_bitlen || !dstbase_bitlen){ | |
throw new Error("length of argument string is too short") | |
} | |
function isUnique(str){ | |
return !str.match(/(.).*\1/) | |
} | |
function isPowerOfTwo(x) { | |
return (x & (x - 1)) == 0; | |
} | |
function zeropad(str, digit){ | |
return ("0".repeat(digit) + str).substr(-digit) | |
} | |
function baseNum(str, is_floor){ | |
var l = str.length | |
return isPowerOfTwo(l) ? l : Math.pow(2, l.toString(2).length - is_floor) | |
} | |
function encode(str){ | |
return str.replace(/./g, function(e){ | |
return zeropad(srcchars.indexOf(e).toString(2), srcbase_bitlen) | |
}).replace(new RegExp(`(.{1,${dstbase_bitlen}}$)|.{${dstbase_bitlen}}`, "g"), function(m, a){ | |
if(a){ | |
return dstchars.charAt(parseInt(m, 2)) + dstchars.charAt(m.length) | |
}else{ | |
return dstchars.charAt(parseInt(m, 2)) | |
} | |
}) | |
} | |
function decode(str){ | |
return str.replace(/(.)(.)$|./g, function(m, a, b){ | |
if(a){ | |
return zeropad(dstchars.indexOf(a).toString(2), dstbase_bitlen).substr(-dstchars.indexOf(b)) | |
}else{ | |
return zeropad(dstchars.indexOf(m).toString(2), dstbase_bitlen) | |
} | |
}).replace(new RegExp(`.{${srcbase_bitlen}}`, "g"), function(e){ | |
return srcchars.charAt(parseInt(e, 2)) | |
}) | |
} | |
return { | |
encode, | |
decode, | |
srcbase, | |
dstbase, | |
srcbase_bitlen, | |
dstbase_bitlen | |
} | |
} |
This file contains 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 barc = basetrans("0123", "0123456789abcdefghijklmnopqrstuvwxyz") | |
var d = "330120" | |
var e = barc.encode(d) | |
var r = barc.decode(e) | |
console.log(d, e, r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment