1
0
Fork 0
forked from 0x2620/oxjs

change base 26 to bijective base 26

This commit is contained in:
rolux 2011-12-17 04:33:43 +05:30
commit 6374f6de6d
4 changed files with 24 additions and 13 deletions

View file

@ -42,26 +42,32 @@
}
/*@
Ox.encodeBase26 <b> Encode a number as base26
> Ox.encodeBase26(3758)
Ox.encodeBase26 <b> Encode a number as bijective base26
See <a href="http://en.wikipedia.org/wiki/Bijective_numeration">
Bijective numeration</a>.
> Ox.encodeBase26(4461)
'FOO'
@*/
Ox.encodeBase26 = function(num) {
return Ox.map(num.toString(26), function(char) {
return Ox.char(65 + parseInt(char, 26));
}).join('');
var ret = '';
while (num) {
ret = String.fromCharCode(64 + num % 26) + ret;
num = parseInt(num / 26);
}
return ret;
};
/*@
Ox.decodeBase26 <f> Decodes a base26-encoded number
See <a href="http://www.crockford.com/wrmg/base32.html">Base 32</a>.
Ox.decodeBase26 <f> Decodes a bijective base26-encoded number
See <a href="http://en.wikipedia.org/wiki/Bijective_numeration">
Bijective numeration</a>.
> Ox.decodeBase26('foo')
3758
4461
@*/
Ox.decodeBase26 = function(str) {
return parseInt(Ox.map(str.toUpperCase(), function(char) {
return (char.charCodeAt(0) - 65).toString(26);
}).join(''), 26);
return str.toUpperCase().split('').reverse().reduce(function(p, v, i) {
return p + (v.charCodeAt(0) - 64) * Math.pow(26, i);
}, 0);
};
/*@