Skip to content

Instantly share code, notes, and snippets.

@menangen
Created December 27, 2018 17:32
Show Gist options
  • Save menangen/d7e5cbb9474f968dcef435f1844cb39c to your computer and use it in GitHub Desktop.
Save menangen/d7e5cbb9474f968dcef435f1844cb39c to your computer and use it in GitHub Desktop.
Human ready Base32 node.js
const assert = require('assert');
class Encoder {
static get alpha () {
return "0123456789ABCDEFGHJKLMNPQRSTVXYZ"
}
static getCode(number) {
const r = number & 31;
const diff = (number - r) >> 5;
if (diff == 0) {
return Encoder.toChar(r);
}
return Encoder.getCode( diff ) + Encoder.toChar(r);
}
static toChar(n) {
return Encoder.alpha.charAt(n);
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
assert.strictEqual(Encoder.getCode(65535), "1ZZZ");
assert.strictEqual(Encoder.getCode(1234), "16J");
assert.strictEqual(Encoder.getCode(256), "80");
assert.strictEqual(Encoder.getCode(10000), "9QG");
assert.strictEqual(Encoder.getCode(20000), "KH0");
for (let i=0; i < 10; i++) console.log(Encoder.getCode(randomInt(0, 65535)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment